﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;
using MES.DataGateway.SyncEntity;
using System.Xml;
using MES.DataGateway.Common;
using MES.DataGateway.OracleDAL;
using MES.DataGateway.SyncCommon;
using MES.DataGateway.SyncInterface;
using MES.DataGateway.StandardEntity;
using System.IO;
using System.Configuration;
using System.Diagnostics;

namespace MES.DataGateway.StandardDataSync
{
    public class WorkFlow : SyncInfterface
    {
        private AssistantClass m_Assistant = new AssistantClass();
        private TreeView trvMes = new TreeView();
        private TreeView trvEnterprise = new TreeView();
        private ServiceEntity m_ServiceInfoEntity = null;
        private string m_ProjectID = "";
        private string m_LibID = "";
        private int m_CryNumber = 0;
        private string m_DataFilePath = "";
        private string m_StrDocumentName = "";
        private string m_StrWorkFlowDocumentName = "";
        private string m_AccessoriesPath = "";
        private string m_TempPath = "";
        private string m_strWorkFlowForProduct = "";
        private string m_strWorkFlowForProductVer = "";
        private OutInfoEntity m_OutParameterObject = null;
        private List<OutInfoEntity> m_OutParameterObjectList = new List<OutInfoEntity>();
        private string m_SyncType = "1";
        private bool m_CreateSubWorkflow = false;
        private string m_FileName = "";//add:Wangjh 2017-9-15
        private string m_ProcessNo = "";//工艺号 YangSJ-11-10
        private string m_ProcessPlant = "";//工艺车间 YangSJ-11-10
        private string m_FaProcessNo = "";//父工艺名 add:Wangjh 201801207
        private string m_FaProcessRev = "";//父工艺版本 add:Wangjh 201801207
        private string m_PdmProductName = "";//pdm推送的件号 add:Wangjh 20181207
        private List<ObjectDocumentEntity> m_ObjectFileInfo=new List<ObjectDocumentEntity>();//对象附件信息 add:wangjh 20211101
        private string m_workflowName = "";//add:wangjh 20211101
        private string m_workflowRev = "";//add:wangjh 20211101
        private ExecuteAPI m_excAPI;
        private StandardDAL m_DAL;
        private XmlDocument m_myXml;//add:Wangjh 20220901
        private const string m_gzPlant = "604";//工装工具分公司的分厂代码

        #region 属性
        public string SyncType
        {
            get { return m_SyncType; }
            set { m_SyncType = value; }
        }

        public OutInfoEntity OutParameterObject
        {
            get { return m_OutParameterObject; }
        }

        public List<OutInfoEntity> OutParameterObjectList
        {
            get { return m_OutParameterObjectList; }
        }

        public string AccessoriesPath
        {
            set { m_AccessoriesPath = value; }
        }

        public ServiceEntity ServiceInfoEntity
        {
            get { return m_ServiceInfoEntity; }
            set { m_ServiceInfoEntity = value; }
        }

        public string ProjectID
        {
            get { return m_ProjectID; }
            set { m_ProjectID = value; }
        }

        public string LibID
        {
            get { return m_LibID; }
            set { m_LibID = value; }
        }

        public string DataFilePath
        {
            get { return m_DataFilePath; }
            set { m_DataFilePath = value; }
        }
        #endregion

        public void Execute()
        {
            m_Assistant.DataFilePath = m_DataFilePath;
            m_Assistant.ServiceInfoEntity = m_ServiceInfoEntity;
            m_Assistant.LibID = m_LibID;
            m_Assistant.ProjectID = m_ProjectID;
            m_Assistant.LoadXmlData(trvMes, trvEnterprise);
            m_TempPath = ConfigurationManager.AppSettings["CamstarPathTemp"];
            m_FileName = Path.GetFileName(m_DataFilePath);//add:Wangjh 2017-9-15
            Log.SetConfig();//add:Wangjh 
            m_excAPI = new ExecuteAPI();
            m_DAL = new StandardDAL();
            m_myXml = new XmlDocument();
            m_myXml.Load(m_DataFilePath);//add:Wangjh 20220901

            try
            {
                LoadSpec();
                try
                {
                    LoadWorkFlowDocumentSet();//工艺上的附件
                }
                catch (Exception ex)
                {
                    Log.WriteLog(ex.Message, 0, "WorkflowDocuments");
                    Log.WriteOrcaleError("PDMTOMES_WorkflowDocuments" + "@^" + ex.Message + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                }
              
                LoadSubWorkflowByMEOP();
                LoadWorkFlow();
                LoadSpecResourceGroup();
                SaveDocumentNew(m_ObjectFileInfo);//保存附件，文档不存数据库

                //需要重新循环工序处理一些信息，如：特殊过程，辅材等
                DealMeopSomeInfo();
                //工艺更改单--在制批次暂停
                WorkFlowChangContainerToPause();
                //会签信息
                SaveWorkflowSignatureInfo();
            }
            catch (Exception ex)
            {
                Log.WriteLog (ex.Message,0,"Workflow" );
                Log.WriteOrcaleError("PDMTOMES_WorkFlow" + "@^" + ex.Message +ex.StackTrace  + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
            }

        }

        public void ShowAttribute()
        {
            FrmSetAttribute myForm = new FrmSetAttribute();
            myForm.ServiceKey = "WorkFlow";
            myForm.PrjectID = m_ProjectID;
            myForm.ShowDialog();
        }

        #region 创建workFlow
        /// <summary>
        /// 仅工艺信息获取
        /// </summary>
        /// <param name="mainEntity"></param>
        private void GetWorkFlowData(ref SyncParameterEntity mainEntity)
        {
            string productname = "";//原始件号，会带H  yangsj 2018-4-12
            m_CryNumber = 0;
            mainEntity.OperationKind = "New";
            mainEntity.ServiceKey = "WorkFlow";
            mainEntity.DataList = new List<DataEntity>();
            string strResourceValue = "";
            foreach (TreeNode node in trvMes.Nodes)
            {
                if (node.Text != "WorkFlow")
                    continue;

                foreach (TreeNode childNode in node.Nodes)
                {
                    if (childNode.Text == "File")
                    {
                        #region 赋值
                        if (m_StrWorkFlowDocumentName.Trim() != "")
                        {
                            mainEntity.DataList.Add(new DataEntity("DocumentSet", "namedObjectField", m_StrWorkFlowDocumentName, ""));
                        }
                        #endregion
                    }
                    else if (childNode.Tag.ToString().Trim() == "dataField" || childNode.Tag.ToString().Trim() == "namedObjectField")
                    {
                        #region 赋值
                        string strValue = m_Assistant.GetMappingValue(childNode, trvEnterprise, ref strResourceValue);
                        if (strValue.Trim() != "")
                        {
                            DataEntity entity = new DataEntity(childNode.Text, childNode.Tag.ToString().Trim(), strValue, "");
                            //增加分厂代码转换 add:Wangjh 20180116
                            if (childNode.Text == "Factory")
                            {
                                entity.FieldValue = m_DAL.GetFacorybyCode(strValue);
                            }
                            mainEntity.DataList.Add(entity);
                        }
                        #endregion
                    }
                    else if (childNode.Tag.ToString().Trim() == "revisionedObjectField")
                    {
                        string strName = "";
                        string strVersion = "1";
                        foreach (TreeNode childTwoNode in childNode.Nodes)
                        {
                            #region 赋值
                            if (childTwoNode.Text == "Name")
                            {
                                strName = m_Assistant.GetMappingValue(childTwoNode, trvEnterprise, ref strResourceValue);
                            }
                            else if (childTwoNode.Text == "Revision")
                            {
                                strVersion = m_Assistant.GetMappingValue(childTwoNode, trvEnterprise, ref strResourceValue);
                            }
                            #endregion
                        }
                        if (string.IsNullOrEmpty(strName))
                            continue;
                        //件号直接获取不用解析xml
                        if (childNode.Text == "Product")
                        {
                            productname = strName;
                            strName = m_strWorkFlowForProduct;
                            strVersion = m_strWorkFlowForProductVer;
                        }
                        mainEntity.DataList.Add(new DataEntity(childNode.Text, childNode.Tag.ToString().Trim(), strName, strVersion));
                    }
                }
            }
        }

        private void GetWorkFlowData(ref  List<DataEntity> specList, ref List<DataEntity> stepList, ref SyncParameterEntity mainEntity)
        {            
            m_CryNumber = 0;
            mainEntity.OperationKind = "New";
            mainEntity.ServiceKey = "WorkFlow";
            mainEntity.DataList = new List<DataEntity>();

            foreach (TreeNode node in trvMes.Nodes)
            {
                if (node.Text != "WorkFlow")
                    continue;
                CreateChildWorkFlow(node, mainEntity.DataList, ref stepList, ref specList);
            }
            XmlNode mlgxNode = m_Assistant.GetMLGXNode();//获取毛料工序信息
            if (mlgxNode != null) {
                if (mlgxNode.SelectSingleNode("ly2use_quota") != null)//获取消耗定额 add:Wangjh 20220428
                    mainEntity.DataList.Add(new DataEntity("UseQuota", "dataField", mlgxNode.SelectSingleNode("ly2use_quota").InnerText, ""));
            }
        }

        private void CreateChildWorkFlow(TreeNode node, List<DataEntity> dataList, ref List<DataEntity> stepList, ref List<DataEntity> specList)
        {
            string productname = "";//原始件号，会带H  yangsj 2018-4-12
            foreach (TreeNode childNode in node.Nodes)
            {
                if (childNode.Text == "Documentset")
                {
                    #region 赋值
                    if (m_StrWorkFlowDocumentName.Trim() != "")
                    {
                        dataList.Add(new DataEntity("DocumentSet", "namedObjectField", m_StrWorkFlowDocumentName, ""));
                    }
                    #endregion
                }
                else if (childNode.Tag.ToString().Trim() == "dataField" || childNode.Tag.ToString().Trim() == "namedObjectField")
                {
                    #region 赋值
                    string strResourceValue = "";
                    string strValue = m_Assistant.GetMappingValue(childNode, trvEnterprise, ref strResourceValue);
                    if (strValue.Trim() != "")
                    {
                        DataEntity entity = new DataEntity(childNode.Text, childNode.Tag.ToString().Trim(), strValue, "");
                        if (childNode.Text == "Factory")
                        {
                            string strfactoryname = m_DAL.GetFacorybyCode(strValue);
                            entity.FieldValue = strfactoryname;
                        }
                        else if (childNode.Text == "Team")
                        {
                            bool IsExistTeam = m_DAL.IsExistTeam(m_gzPlant,strValue);
                            entity.FieldValue = IsExistTeam?strValue:null;
                        }
                        else
                            entity.FieldValue = strValue;
                        dataList.Add(entity);
                    }
                    #endregion

                }
                else if (childNode.Tag.ToString().Trim() == "namedObjectList" && childNode.Text == "ProductFamilyList")///工艺多机型管理
                {
                    #region 赋值
                    string strResourceValue = "";
                    string strValue = m_Assistant.GetMappingValue(childNode, trvEnterprise, ref strResourceValue);
                    if (strValue.Trim() != "")
                    {
                        Dictionary<Int32, string> list = new Dictionary<int, string>();
                        int i = 0;
                        foreach (string family in strValue.Split(';'))
                        {
                            if (string.IsNullOrWhiteSpace(family))
                                continue;
                            ProcessPorudctFamily(family);
                            list.Add(i, family);
                            i++;
                        }
                        if (list.Count > 0)
                        {
                            dataList.Add(new DataEntity(childNode.Text, childNode.Tag.ToString().Trim(), list, ""));
                        }
                    }
                    #endregion
                }
                else if (childNode.Tag.ToString().Trim() == "revisionedObjectField")
                {
                    string strName = "";
                    string strVersion = "1";
                    foreach (TreeNode childTwoNode in childNode.Nodes)
                    {
                        #region 赋值

                        if (childTwoNode.Text == "Name")
                        {
                            string strResourceValue = "";
                            strName = m_Assistant.GetMappingValue(childTwoNode, trvEnterprise, ref strResourceValue);
                        }
                        else if (childTwoNode.Text == "Revision")
                        {
                            string strResourceValue = "";
                            strVersion = m_Assistant.GetMappingValue(childTwoNode, trvEnterprise, ref strResourceValue);
                        }

                        #endregion
                    }
                    if (string.IsNullOrEmpty(strName))
                        continue;
                    //件号直接获取不用解析xml
                    if (childNode.Text == "Product")
                    {
                        productname = strName;
                        m_PdmProductName = strName;
                        strName = m_strWorkFlowForProduct;
                        strVersion = m_strWorkFlowForProductVer;
                    }

                    dataList.Add(new DataEntity(childNode.Text, childNode.Tag.ToString().Trim(), strName, strVersion));

                }
                else if (childNode.Text == "Steps")
                {
                    XmlDocument myxml = new XmlDocument();
                    myxml.Load(m_DataFilePath);
                    string strTmp = m_Assistant.GetMappingPath(childNode.Nodes[0].Nodes[0]);
                    m_CryNumber = m_Assistant.GetCryNodeNumber(strTmp, trvEnterprise);
                    int intIntIndex = 0;
                    for (int i = 0; i < m_CryNumber; i++)
                    {
                        foreach (TreeNode stepNameNode in childNode.Nodes[0].Nodes)
                        {
                            if (stepNameNode.Text == "Spec")
                            {
                                #region 赋值
                                DataEntity specEntity = new DataEntity(stepNameNode.Text, stepNameNode.Tag.ToString().Trim(), "", "");

                                string strSpecName = "";
                                string strSpecVersion = "1";
                                string strMappingPath = "";
                                string isCooperation = "";
                                string stepFactory = "";//工序分厂 add:Wangjh 20180110
                                string faMeopNo = "";//父工序号 add:Wangjh 20181207
                                //add:Wangjh 20181227 获取item_ID
                                string item_ID = "";
                                try { item_ID = myxml.SelectNodes("/Root/WorkFlow/MEOPs/MEOP/item_id")[i].InnerText; }
                                catch (Exception) { }
                                //
                                specEntity.IndexNo = intIntIndex;
                                foreach (TreeNode specNode in stepNameNode.Nodes)
                                {
                                    strMappingPath = m_Assistant.GetMappingPath(specNode);
                                    if (strMappingPath.Trim() == "")
                                        continue;
                                    if (specNode.Text == "Name")
                                    {
                                        strSpecName = m_Assistant.GetCryValue(strMappingPath, intIntIndex, trvEnterprise);
                                        strSpecName = m_Assistant.PatchNameByCly(strSpecName, specNode.FullPath, intIntIndex, trvEnterprise);
                                    }
                                    else if (specNode.Text == "Revision")
                                    {
                                        strSpecVersion = m_Assistant.GetCryValue(strMappingPath, intIntIndex, trvEnterprise);
                                    }
                                    else if (specNode.Text == "IsCooperation")
                                    {
                                        isCooperation = m_Assistant.GetCryValue(strMappingPath, intIntIndex, trvEnterprise);
                                    }
                                    else if (specNode.Text == "Factory")
                                    {
                                        stepFactory = m_Assistant.GetCryValue(strMappingPath, intIntIndex, trvEnterprise);
                                    }
                                    else if (specNode.Text == "ParentSpecNo") 
                                    {
                                        faMeopNo = m_Assistant.GetCryValue(strMappingPath, intIntIndex, trvEnterprise);
                                    }
                                    else if (specNode.Text == "commonsubworkflow")//通用工艺
                                    {
                                        var commonSub = m_Assistant.GetCryValue(strMappingPath, intIntIndex, trvEnterprise);
                                        if (!string.IsNullOrWhiteSpace(commonSub))
                                        {
                                            specEntity.IsSubStep = true;                                            
                                        }
                                    }
                                }
                                strMappingPath = m_Assistant.GetMappingPath(stepNameNode);
                                if (isCooperation == "Y")//工序有子工艺
                                    specEntity.IsSubStep = true ;
                                if (faMeopNo != "")
                                    specEntity.FaMeopNo = faMeopNo;
                                
                                //if (isCooperation == "Y")
                                //{
                                //    specEntity.FieldName = "SubWorkflow";
                                //    //工艺上一版本存在工序子工艺直接关联 yangsj 2018-3-27
                                //    GetSubWorkflowOldVersion(dataList, stepList[stepList.Count - 1].FieldValue.ToString(), out strSpecName, out strSpecVersion);
                                //    if (string.IsNullOrWhiteSpace(strSpecName))
                                //    {
                                //        strSpecName = "空子工艺";
                                //        strSpecVersion = "00";
                                //        DataTable dt=m_DAL.GetSubWorkflowEmpty ();
                                //        //空子工艺根据分厂添加 add:Wangjh 20180108
                                //        //switch (stepFactory)
                                //        //{
                                //        //    case "600": strSpecVersion = "05"; break;//
                                //        //    case "601": strSpecVersion = "02"; break;//
                                //        //    case "602": strSpecVersion = "04"; break;//
                                //        //    case "603": strSpecVersion = "07"; break;//
                                //        //    case "607": strSpecVersion = "03"; break;//
                                //        //    case "609": strSpecVersion = "01"; break;//
                                //        //}
                                //        DataRow[] drs= dt.Select("attributevalue='" + stepFactory + "'");
                                //        if (drs.Length > 0)
                                //            strSpecVersion = drs[0]["workflowrevision"].ToString ();
                                //        if (strSpecVersion.ToString() != "00")
                                //        {
                                //            strSpecName = "空子工艺临时";
                                //        }
                                //    }
                                //    //stepFactory = "";
                                //}

                                specEntity.IndexNo = intIntIndex;
                                specEntity.FieldValue = strSpecName + "-" + item_ID;
                                specEntity.FileldVersion = strSpecVersion;
                                specEntity.SpecFactoryCode = stepFactory;//add:Wangjh 2018/10/8 增加分厂属性
                                specEntity.Item_ID = item_ID;
                                specList.Add(specEntity);
                                #endregion
                            }
                            else
                            {
                                int intNumber = 0;
                                string strMappingPath = m_Assistant.GetMappingPath(stepNameNode);
                                m_Assistant.CheckNodeCryNumber(strMappingPath, trvEnterprise, ref intNumber);
                                if (intNumber <= 1)
                                {
                                    #region 赋值
                                    string strResourceValue = "";
                                    string strValue = m_Assistant.GetMappingValue(stepNameNode, trvEnterprise, ref strResourceValue);
                                    strValue = strValue.Replace(productname + "-", "");//按原始件号替换 Yangsj 2018-4-12
                                    if (strValue.Trim() != "")
                                    {
                                        stepList.Add(new DataEntity(stepNameNode.Text, stepNameNode.Tag.ToString().Trim(), strValue, ""));
                                    }
                                    #endregion
                                }
                                else
                                {
                                    #region 赋值
                                    string strMapping1Path = m_Assistant.GetMappingPath(stepNameNode);
                                    if (strMapping1Path.Trim() != "")
                                    {
                                        string value = m_Assistant.GetCryValue(strMapping1Path, intIntIndex, trvEnterprise);
                                        value = m_Assistant.PatchNameByCly(value, stepNameNode.FullPath, intIntIndex, trvEnterprise);
                                        value = value.Replace(productname + "-", "");//按原始件号替换 Yangsj 2018-4-12
                                        stepList.Add(new DataEntity(stepNameNode.Text, stepNameNode.Tag.ToString().Trim(), value, ""));
                                    }
                                    #endregion
                                }
                            }
                        }
                        intIntIndex = intIntIndex + 1;
                    }
                }
            }
        }
        #endregion


        //检查是否有productfamile 没有则添加
        private void ProcessPorudctFamily(string strProductFamily)
        {
            DataSet ds = m_DAL.GetProductFamily(strProductFamily);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return;
            }
            else
            {
                OutInfoEntity infoEntity = new OutInfoEntity();
                m_excAPI.CreateNDOData("ProductFamily", strProductFamily, ref infoEntity);
                m_OutParameterObjectList.Add(infoEntity);
                if (infoEntity.OutFlag == 1)//add:Wangjh 2017-9-15 
                {
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer );//add:Wangjh 写入数据库   
                }
                else
                {
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + "ProductFamily创建失败:" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                }
            }
        }
        #region 建立Spec设备组
        void LoadSpecResourceGroup()
        {
            OutInfoEntity outInfo;
            foreach (TreeNode MeopsNode in trvEnterprise.Nodes)
            {
                if (MeopsNode.Text == "MEOPs")
                {
                    foreach (TreeNode Meop in MeopsNode.Nodes)
                    {
                        string SpecName = "";
                        string SpecRev = "";
                        DataTable ResDT = new DataTable();
                        ResDT.Columns.Add("Name");
                        ResDT.Columns.Add("revision");
                        ResDT.Columns.Add("Description");
                        ResDT.Columns.Add("ufcResourceAlias");
                        ResDT.Columns.Add("ufcResourceNo");
                        ResDT.Columns.Add("equipspec");
                        ResDT.Columns.Add("equipprecision");

                        #region 赋值
                        foreach (TreeNode docNode in Meop.Nodes)
                        {
                            if (docNode.Text == "Name")
                            {
                                SpecName = docNode.Tag.ToString();
                            }
                            if (docNode.Text == "Item_revision_id")
                            {
                                SpecRev = docNode.Tag.ToString();
                            }
                            if (docNode.Text == "Resources")
                            {
                                foreach (TreeNode resNode in docNode.Nodes)
                                {
                                    DataRow dr = ResDT.NewRow();
                                    foreach (TreeNode resField in resNode.Nodes)
                                    {
                                        if (resField.Text == "Item_id")
                                        {
                                            dr["Name"] = resField.Tag.ToString();

                                        }
                                        if (resField.Text == "Item_revision_id")
                                        {
                                            dr["revision"] = resField.Tag.ToString();
                                        }

                                        if (resField.Text == "object_name")
                                        {
                                            dr["Description"] = resField.Tag.ToString();
                                        }

                                        if (resField.Text == "ht6_equip_type")
                                        {
                                            dr["ufcResourceAlias"] = resField.Tag.ToString();
                                        }

                                        if (resField.Text == "ht6_equip_no")
                                        {
                                            dr["ufcResourceNo"] = resField.Tag.ToString();
                                        }
                                        if (resField.Text == "ht6_equip_spec")
                                        {
                                            dr["equipspec"] = resField.Tag.ToString();
                                        }

                                        if (resField.Text == "ht6_equip_precision")
                                        {
                                            dr["equipprecision"] = resField.Tag.ToString();
                                        }
                                    }
                                    ResDT.Rows.Add(dr);





                                }
                            }
                        }
                        #endregion

                        for (int k = 0; k < ResDT.Rows.Count; k++)
                        {
                            DataSet ds = m_DAL.GetResource(ResDT.Rows[k]["Name"].ToString());
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                Log.WriteLog("设备" + ResDT.Rows[k]["Name"].ToString() + "已经存在，跳过处理", 0, "创建设备");
                                Log.WriteOrcale("PDMTOMES_ResourceGroup" + "@^" + "设备" + ResDT.Rows[k]["Name"].ToString() + "已经存在，跳过处理" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库
                                continue;
                            }
                            else
                            {
                                SyncParameterEntity resMainEntity = new SyncParameterEntity();
                                resMainEntity.OperationKind = "New";
                                resMainEntity.ServiceKey = "Resource";
                                resMainEntity.DataList = new List<DataEntity>();

                                DataEntity resentity = new DataEntity();
                                resentity.FieldName = "Name";
                                resentity.FieldType = "dataField";
                                resentity.FieldValue = ResDT.Rows[k]["Name"].ToString();
                                resentity.FileldVersion = "";
                                resMainEntity.DataList.Add(resentity);

                                resentity = new DataEntity();
                                resentity.FieldName = "revision";
                                resentity.FieldType = "dataField";
                                resentity.FieldValue = ResDT.Rows[k]["revision"].ToString();
                                resentity.FileldVersion = "";
                                resMainEntity.DataList.Add(resentity);

                                resentity = new DataEntity();
                                resentity.FieldName = "Description";
                                resentity.FieldType = "dataField";
                                resentity.FieldValue = ResDT.Rows[k]["Description"].ToString();
                                resentity.FileldVersion = "";
                                resMainEntity.DataList.Add(resentity);

                                resentity = new DataEntity();
                                resentity.FieldName = "ufcResourceAlias";
                                resentity.FieldType = "dataField";
                                resentity.FieldValue = ResDT.Rows[k]["ufcResourceAlias"].ToString();
                                resentity.FileldVersion = "";
                                resMainEntity.DataList.Add(resentity);

                                resentity = new DataEntity();
                                resentity.FieldName = "ufcResourceNo";
                                resentity.FieldType = "dataField";
                                resentity.FieldValue = ResDT.Rows[k]["ufcResourceNo"].ToString();
                                resentity.FileldVersion = "";
                                resMainEntity.DataList.Add(resentity);

                                resentity = new DataEntity();
                                resentity.FieldName = "equipspec";
                                resentity.FieldType = "dataField";
                                resentity.FieldValue = ResDT.Rows[k]["equipspec"].ToString();
                                resentity.FileldVersion = "";
                                resMainEntity.DataList.Add(resentity);

                                resentity = new DataEntity();
                                resentity.FieldName = "equipprecision";
                                resentity.FieldType = "dataField";
                                resentity.FieldValue = ResDT.Rows[k]["equipprecision"].ToString();
                                resentity.FileldVersion = "";
                                resMainEntity.DataList.Add(resentity);
                                outInfo = new OutInfoEntity();
                                m_excAPI.CreateNDOEntity("Resource", resMainEntity, ref outInfo);
                                if (outInfo.OutFlag == 1)//add:Wangjh 2017-9-15 
                                {
                                    Log.WriteOrcale("PDMTOMES_" + outInfo.StrServicekey + "@^" + outInfo.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                                }
                                else if (outInfo.OutFlag == 2)
                                {
                                    Log.WriteOrcale("PDMTOMES_" + outInfo.StrServicekey + "@^" + "Resource创建失败:" + outInfo.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                                }
                            }
                        }

                        if (ResDT.Rows.Count == 0)
                        {
                            continue;
                        }

                        outInfo = new OutInfoEntity();
                        m_excAPI.CreateResourceGroup(ResDT, SpecName, ref outInfo);
                        if (outInfo.OutFlag == 1)//add:Wangjh 2017-9-15 
                        {
                            Log.WriteOrcale("PDMTOMES_" + outInfo.StrServicekey + "@^" + outInfo.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                        }
                        else if (outInfo.OutFlag == 2)
                        {
                            Log.WriteOrcale("PDMTOMES_" + outInfo.StrServicekey + "@^" + "ResourceGroup创建失败:" + outInfo.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                        }


                        SyncParameterEntity SpecEntiry = new SyncParameterEntity();
                        SpecEntiry.DataList = new List<DataEntity>();

                        DataEntity SpecGroup = new DataEntity();
                        SpecGroup.FieldName = "ResourceGroup";
                        SpecGroup.FieldType = "namedObjectField";
                        SpecGroup.FieldValue = SpecName;
                        SpecGroup.FileldVersion = "";
                        SpecEntiry.DataList.Add(SpecGroup);

                        outInfo = new OutInfoEntity();
                        m_excAPI.UpdateRDOEntity("Spec", SpecName, SpecRev, SpecEntiry, ref outInfo);
                        if (outInfo.OutFlag == 1)//add:Wangjh 2017-9-15 
                        {
                            Log.WriteOrcale("PDMTOMES_" + outInfo.StrServicekey + "@^" + outInfo.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                        }
                        else if (outInfo.OutFlag == 2)
                        {
                            Log.WriteOrcale("PDMTOMES_" + outInfo.StrServicekey + "@^" + "spec修改失败:" + outInfo.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                        }

                    }
                }
            }


        }

        #endregion

        #region 建立spec
        private void LoadSpec()
        {
            XmlDocument myxml = new XmlDocument();
            myxml.Load(m_DataFilePath);
            XmlNode stu = myxml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/ly2process_no");
            m_ProcessNo = stu.InnerText;
            stu = myxml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/ly2plant");
            m_ProcessPlant = stu.InnerText;
            m_CryNumber = 0;

            List<SyncParameterEntity> specList = new List<SyncParameterEntity>();
            TreeNode specNode = new TreeNode();
            string strFactoryName = "";//工艺分厂
            string strResourceValue = "";
            foreach (TreeNode node in trvMes.Nodes)
            {
                if (node.Text != "WorkFlow")
                    continue;
                foreach (TreeNode wChildNode in node.Nodes)  //workFlow下面业务数据处理
                {
                    if (wChildNode.Text == "Factory")
                        strFactoryName = m_Assistant.GetMappingValue(wChildNode, trvEnterprise, ref strResourceValue);
                    else if (wChildNode.Text == "Steps")
                    { specNode = wChildNode; }
                    else if (wChildNode.Text == "Product")
                    {
                        foreach (TreeNode pChildNode in wChildNode.Nodes)
                        {
                            if (pChildNode.Text == "Name")
                            {
                                m_strWorkFlowForProduct = m_Assistant.GetMappingValue(pChildNode, trvEnterprise, ref strResourceValue);
                                m_Assistant.ReplaceProductH(null, ref m_strWorkFlowForProduct);
                            }
                            else if (pChildNode.Text == "Revision")
                                m_strWorkFlowForProductVer = m_Assistant.GetMappingValue(pChildNode, trvEnterprise, ref strResourceValue);
                        }
                    }
                }

            }
            string strTmp = m_Assistant.GetMappingPath(specNode.Nodes[0].Nodes[0]);
            // strTmp = @"WorkFlow\MEOPs\MEOP\object_name";
            m_CryNumber = m_Assistant.GetCryNodeNumber(strTmp, trvEnterprise);
            FillSpecRDOList(specList, specNode, false);

            strTmp = @"WorkFlow\MEOPs\MEOP\ChildProcesss\ChildMEOPs\MEOP\object_name";
            m_CryNumber = m_Assistant.GetCryNodeNumber(strTmp, trvEnterprise);
            if (m_CryNumber > 0)
                FillSpecRDOList(specList, specNode, true);

            for (int i = 0; i < specList.Count; i++)
            {
                SyncParameterEntity tmpEntity = specList[i];
                string strSpecName = "";
                string strSpecVersion = "1";
                bool isSubWorkflow = false;
                foreach (DataEntity _tmpEntity in tmpEntity.DataList)
                {
                    if (string.IsNullOrEmpty(_tmpEntity.FieldValue.ToString()))
                        continue;
                    //处理Name和Revision
                    if (_tmpEntity.FieldName == "Name")
                    {
                        _tmpEntity.FieldValue = _tmpEntity.FieldValue + "-" + _tmpEntity.Item_ID;
                        strSpecName = _tmpEntity.FieldValue.ToString().Trim();
                    }
                    else if (_tmpEntity.FieldName == "Revision")
                    {
                        strSpecVersion = _tmpEntity.FieldValue.ToString().Trim();
                    }
                    else if (_tmpEntity.FieldName == "IsCooperation")
                    {
                        if (_tmpEntity.FieldValue.ToString().Trim() == "1" || _tmpEntity.FieldValue.ToString().Trim() == "Y" || _tmpEntity.FieldValue.ToString().Trim() == "协作")
                        {
                            _tmpEntity.FieldValue = "1";
                            isSubWorkflow = true;
                        }
                        else
                            _tmpEntity.FieldValue = "0";
                    }
                    else if (_tmpEntity.FieldName == "IsKey")
                    {
                        if (_tmpEntity.FieldValue.ToString().Trim() == "1" || _tmpEntity.FieldValue.ToString().Trim() == "Y" || _tmpEntity.FieldValue.ToString().Trim() == "关键工序")
                            _tmpEntity.FieldValue = "1";
                        else
                            _tmpEntity.FieldValue = "0";
                    }
                    else if (_tmpEntity.FieldName == "IsSpotCheck")
                    {
                        if (_tmpEntity.FieldValue.ToString().Trim() == "1" || _tmpEntity.FieldValue.ToString().Trim() == "Y" || _tmpEntity.FieldValue.ToString().Trim() == "是")
                            _tmpEntity.FieldValue = "1";
                        else
                            _tmpEntity.FieldValue = "0";
                    }
                    else if (_tmpEntity.FieldName == "NCNumber")
                    {
                        if (_tmpEntity.FieldValue.ToString().Trim() == "Y")
                            _tmpEntity.FieldValue = "1";
                        else
                            _tmpEntity.FieldValue = "0";
                    }
                    else if (_tmpEntity.FieldName == "LastCheck")
                    {
                        if (_tmpEntity.FieldValue.ToString().Trim() == "检验工序" || _tmpEntity.FieldValue.ToString().Trim() == "检测工序")
                            _tmpEntity.FieldValue = "1";
                        else
                            _tmpEntity.FieldValue = "0";
                    }
                    if (_tmpEntity.FieldType != "namedObjectField")
                    {
                        continue;
                    }
                    if (_tmpEntity.FieldName == "Factory")//分厂属性代码转换YangSJ 2017-11-10
                    {
                        string factoryname = ProcessNDOEntity(_tmpEntity.FieldName, _tmpEntity.FieldName + "name", _tmpEntity.FieldValue.ToString().Trim());
                        if (!string.IsNullOrWhiteSpace(factoryname))
                            _tmpEntity.FieldValue = factoryname;
                        continue;
                    }
                    ProcessNDOEntity(_tmpEntity.FieldName, _tmpEntity.FieldName + "name", _tmpEntity.FieldValue.ToString().Trim());
                }
                //if (isSubWorkflow)//工序有子工艺则不创建SPEC
                //    continue;
                DataSet specSet = m_DAL.GetSpecInfo(strSpecVersion, strSpecName);

                if (specSet.Tables[0].Rows.Count == 0)
                {
                    DataSet specSet1 = m_DAL.GetSpecInfo(strSpecName);
                    OutInfoEntity myEntity = new OutInfoEntity();
                    if (specSet1.Tables[0].Rows.Count > 0)
                    {
                        string strOldVersion = m_DAL.GetSpecVersion(strSpecName);
                        m_excAPI.CreateSpecVersion(strSpecName, strOldVersion, specList[i], ref myEntity);
                        if (myEntity.OutFlag == 2)
                            myEntity.StrInfo = strSpecName + ",版本：" + strSpecVersion + "Spec版本添加失败:" + myEntity.StrInfo;
                    }
                    else
                    {
                        m_excAPI.CreateSpec(specList[i], ref myEntity);
                        if (myEntity.OutFlag == 2)
                            myEntity.StrInfo =strSpecName + ",版本：" + strSpecVersion+ "Spec创建失败:" + myEntity.StrInfo;
                    }
                    Log.WriteOrcale("PDMTOMES_" + myEntity.StrServicekey + "@^" + strSpecName + ",版本：" + strSpecVersion + myEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                    //工序创建成功后存入设备信息ly2equipment叶片的设备信息 add:Wangjh 20211214
                    if (myEntity.OutFlag == 1) 
                    {
                        m_DAL.SaveSpecResourceByly2equipment(strSpecName, strSpecVersion);
                    }
                }
            }
        }

        private void FillSpecRDOList(List<SyncParameterEntity> specList, TreeNode specNode, bool isSubSpec)
        {
            XmlDocument myxml = new XmlDocument();
            myxml.Load(m_DataFilePath);
            for (int i = 0; i < m_CryNumber; i++)
            {
                SyncParameterEntity specMainEntity = new SyncParameterEntity();
                specMainEntity.DataList = new List<DataEntity>();
                string strSpecVersion = "";//工序版本
                string specName = "";//工序名称 add:Wangjh 20211101
                List<string> FilesNameList = new List<string>();//每个工序对应的文档列表
                string item_ID = "";
                try { item_ID = myxml.SelectNodes("/Root/WorkFlow/MEOPs/MEOP/item_id")[i].InnerText; }
                catch (Exception) { }

                foreach (TreeNode stepNameNode in specNode.Nodes[0].Nodes)
                {
                    if (stepNameNode.Text != "Spec")
                        continue;
                    string strTmpName = "";
                    strSpecVersion = "";//工序版本
                    specName = "";//工序名称 add:Wangjh 20211101
                    FilesNameList = new List<string>();
                    //add:Wangjh 20181227 获取item_ID
                    
                    foreach (TreeNode specChild in stepNameNode.Nodes)
                    {
                        if (specChild.Text == "Revision")
                        {
                            #region 赋值
                            string strMapping1Path = m_Assistant.GetMappingPath(specChild);

                            if (strMapping1Path.Trim() != "")
                            {
                                if (isSubSpec)
                                    strMapping1Path = strMapping1Path.Replace(@"\MEOP\", @"\MEOP\ChildProcesss\ChildMEOPs\MEOP\");

                                string value = m_Assistant.GetCryValue(strMapping1Path, i, trvEnterprise);
                                DataEntity tmpEntity = new DataEntity(specChild.Text, specChild.Tag.ToString().Trim(), "", "");
                                if (value.Trim() != "")
                                {
                                    tmpEntity.FieldValue = value;
                                    strSpecVersion = value;
                                }
                                else
                                {
                                    tmpEntity.FieldValue = "1";
                                    strSpecVersion = "1";
                                }
                                specMainEntity.DataList.Add(tmpEntity);
                            }
                            else
                            {
                                strSpecVersion = "1";
                                specMainEntity.DataList.Add(new DataEntity(specChild.Text, specChild.Tag.ToString().Trim(), "1", ""));
                            }
                            #endregion
                        }
                        else if (specChild.Text == "SpecNO")
                        {
                            string strMapping1Path = m_Assistant.GetMappingPath(specChild);
                            if (strMapping1Path.Trim() != "")
                            {
                                if (isSubSpec)
                                    strMapping1Path = strMapping1Path.Replace(@"\MEOP\", @"\MEOP\ChildProcesss\ChildMEOPs\MEOP\");

                                string value = m_Assistant.GetCryValue(strMapping1Path, i, trvEnterprise);
                                strTmpName = value;
                            }
                            continue;
                        }
                        else if (specChild.Text == "Documentset")
                        {
                            #region 文档处理
                            //int Index = 0;
                            //TreeNode docsNode = trvEnterprise.Nodes[trvEnterprise.Nodes.Count - 1];

                            //TreeNode currentOPNode = new TreeNode();

                            //foreach (TreeNode MeopsNode in docsNode.Nodes)
                            //{
                            //    if (MeopsNode.Text != "MEOPs")
                            //        continue;
                            //    foreach (TreeNode Meop in MeopsNode.Nodes)
                            //    {
                            //        if (isSubSpec)
                            //        {
                            //            foreach (TreeNode _Meop in Meop.Nodes)
                            //            {
                            //                if (_Meop.Text != "ChildProcesss")
                            //                    continue;
                            //                foreach (TreeNode CPNode in _Meop.Nodes)
                            //                {
                            //                    if (CPNode.Text != "ChildMEOPs")
                            //                        continue;
                            //                    foreach (TreeNode CPOPNode in CPNode.Nodes)
                            //                    {
                            //                        if (CPOPNode.Text != "MEOP")
                            //                            continue;
                            //                        if (Index == i) //如果遍历次数相同则说明Spec对应，处理
                            //                        {
                            //                            currentOPNode = CPOPNode;
                            //                            break;
                            //                        }
                            //                        Index++;
                            //                    }
                            //                    if (currentOPNode.TreeView != null)
                            //                        break;

                            //                }
                            //                if (currentOPNode.TreeView != null)
                            //                    break;
                            //            }
                            //        }
                            //        else
                            //        {
                            //            if (Index == i) //如果遍历次数相同则说明Spec对应，处理
                            //            {
                            //                currentOPNode = Meop;
                            //                break;
                            //            }
                            //            Index++;
                            //        }
                            //        if (currentOPNode.TreeView != null)
                            //            break;
                            //    }
                            //}


                            //foreach (TreeNode docNode in currentOPNode.Nodes)
                            //{
                            //    if (docNode.Text != "Documents")
                            //        continue;
                            //    foreach (TreeNode fileNode in docNode.Nodes)
                            //    {
                            //        FilesNameList.Add(fileNode.Tag.ToString());
                            //    }
                            //    break;
                            //}

                            //if (FilesNameList.Count == 0)
                            //{ break; }
                            ////处理工序文档

                            //////update:Wangjh 20180927 增加容错处理
                            ////string specDocumentSetName = " ";
                            ////try { specDocumentSetName = CreateDocumentSet(FilesNameList); }
                            ////catch (Exception ex)
                            ////{
                            ////    Log.WriteLog(ex.Message, 0, "CreateDocumentSet");
                            ////    Log.WriteOrcaleError("PDMTOMES_Workflow_CreateDocumentSet" + "@^" + ex.Message + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库
                            ////}
                            //////
                            ////if (specDocumentSetName != " ")
                            ////{
                            ////    DataEntity entity = new DataEntity();
                            ////    entity.FieldName = "DocumentSet";
                            ////    entity.FieldType = "namedObjectField";
                            ////    entity.FieldValue = specDocumentSetName;
                            ////    entity.FileldVersion = "";
                            ////    specMainEntity.DataList.Add(entity);
                            ////}

                            #endregion

                            #region 文档处理new add:Wangjh 20220901
                            var specDocs = m_myXml.SelectNodes("/Root/WorkFlow/MEOPs/MEOP")[i];
                            GetDocumentList(FilesNameList, specDocs);
                            #endregion
                        }
                        else if (specChild.Text == "SpecType" && m_ProcessPlant=="603")//装试工序类型取另一个字段
                        {
                            string spectype = "";
                            try { spectype = myxml.SelectNodes("/Root/WorkFlow/MEOPs/MEOP/ly2assyprocess_type")[i].InnerText; }
                            catch (Exception) { }

                            DataEntity entity = new DataEntity();
                            entity.FieldName = "SpecType";
                            entity.FieldType = "namedObjectField";
                            entity.FieldValue = spectype;
                            entity.FileldVersion = "";
                            specMainEntity.DataList.Add(entity);

                        }
                        else if (m_ProcessPlant == m_gzPlant && specChild.Text == "ControlCode")//工装工具分公司的controlcode，特殊处理 add:wangjh 20241203
                        {
                            string controlCode = "LY08";//控制码 设置为报工后自动检验
                            string opdesc = "";//取工序名称
                            string isSpecCheck = "";//是否专检
                            try { isSpecCheck = myxml.SelectNodes("/Root/WorkFlow/MEOPs/MEOP/ly2isSpecCheck")[i].InnerText; }
                            catch (Exception) { }
                            try { opdesc = myxml.SelectNodes("/Root/WorkFlow/MEOPs/MEOP/object_name")[i].InnerText; }
                            catch (Exception) { }

                            if (isSpecCheck == "是")
                            {
                                controlCode = "";
                            }
                            if (opdesc == "虚拟序")
                            {
                                controlCode = "LY07";                                
                            }

                            DataEntity entity = new DataEntity();
                            entity.FieldName = specChild.Text;
                            entity.FieldType = specChild.Tag.ToString().Trim();
                            entity.FieldValue = controlCode;
                            entity.FileldVersion = "";
                            entity.Item_ID = item_ID;
                            specMainEntity.DataList.Add(entity);

                        }
                        else
                        {
                            #region 非版本处理
                            if (specChild.Tag.ToString().Trim() == "dataField" || specChild.Tag.ToString().Trim() == "namedObjectField")
                            {
                                int intNumber = 0;
                                string strMappingPath = m_Assistant.GetMappingPath(specChild);
                              
                                m_Assistant.CheckNodeCryNumber(strMappingPath, trvEnterprise, ref intNumber);

                                if (intNumber <= 1)
                                {
                                    #region 赋值
                                    string strResourceValue = "";
                                    string strValue = m_Assistant.GetMappingValue(specChild, trvEnterprise, ref strResourceValue);
                                    if (strValue.Trim() != "")
                                    {
                                        string strFormatValue = m_Assistant.SetFormatSpecInfo(strValue);
                                        DataEntity entity = new DataEntity();
                                        entity.FieldName = specChild.Text;
                                        entity.FieldType = specChild.Tag.ToString().Trim();
                                        entity.FieldValue = strFormatValue;
                                        entity.FileldVersion = "";
                                        entity.Item_ID = item_ID;            //add:Wangjh 20181227 增加item_id
                                        specMainEntity.DataList.Add(entity);

                                        if (specChild.Text == "Name")
                                        {
                                            specName = strFormatValue;//工序名称
                                        }
                                    }
                                    #endregion
                                }
                                else
                                {
                                    #region 赋值
                                    string strMapping1Path = m_Assistant.GetMappingPath(specChild);
                                    if (strMapping1Path.Trim() != "")
                                    {
                                        if (isSubSpec)
                                            strMapping1Path = strMapping1Path.Replace(@"\MEOP\", @"\MEOP\ChildProcesss\ChildMEOPs\MEOP\");
                                        string value = m_Assistant.GetCryValue(strMapping1Path, i, trvEnterprise);
                                        if (isSubSpec)
                                        {
                                            if (specChild.Text == "Name")
                                            {
                                                strMapping1Path = strMapping1Path.Replace(@"\object_name", @"\item_id");
                                                value = m_Assistant.GetCryValue(strMapping1Path, i, trvEnterprise);
                                            }
                                            else if (specChild.Text == "Description")
                                            {
                                                strMapping1Path = strMapping1Path.Replace(@"\item_id", @"\object_name");
                                                value = string.Format("{1}({0})", value, m_Assistant.GetCryValue(strMapping1Path, i, trvEnterprise));
                                            }

                                        }
                                        else
                                            value = m_Assistant.PatchNameByCly(value, specChild.FullPath, i, trvEnterprise);

                                        if (specChild.Text == "Factory" && string.IsNullOrWhiteSpace(value))//没有对应车间取工艺车间 Yangsj 2017-11-10
                                            value = m_ProcessPlant;
                                        if (value.Trim() != "")
                                        {
                                            string strFormatValue = m_Assistant.SetFormatSpecInfo(value);

                                            DataEntity tmpEntity = new DataEntity();
                                            tmpEntity.FieldName = specChild.Text;
                                            tmpEntity.FieldType = specChild.Tag.ToString().Trim();
                                            tmpEntity.FileldVersion = "";
                                            tmpEntity.FieldValue = strFormatValue;
                                            tmpEntity.Item_ID = item_ID;            //add:Wangjh 20181227 增加item_id
                                            specMainEntity.DataList.Add(tmpEntity);

                                            if (specChild.Text == "Name")
                                            {
                                                specName = strFormatValue;//工序名称
                                            }
                                        }
                                       
                                    }
                                    #endregion
                                }
                            }
                            else if (specChild.Tag.ToString().Trim() == "revisionedObjectField")
                            {
                                #region 赋值
                                foreach (TreeNode childNode in specChild.Nodes)
                                {
                                    string strName = "";
                                    string strVersion = "1";
                                    string strMappingPath = m_Assistant.GetMappingPath(childNode);
                                    if (isSubSpec)
                                        strMappingPath = strMappingPath.Replace(@"\MEOP\", @"\MEOP\ChildProcesss\ChildMEOPs\MEOP\");

                                    if (childNode.Text == "Name")
                                    {
                                        if (strMappingPath.Trim() != "")
                                        {
                                            strName = m_Assistant.GetCryValue(strMappingPath, i, trvEnterprise);
                                            if (!isSubSpec)
                                                strName = m_Assistant.PatchNameByCly(strName, childNode.FullPath, i, trvEnterprise);
                                        }
                                    }
                                    else if (childNode.Text == "Revision")
                                    {
                                        if (strMappingPath.Trim() != "")
                                        {
                                            strVersion = m_Assistant.GetCryValue(strMappingPath, i, trvEnterprise);
                                        }
                                    }

                                    if (strName.Trim() != "")
                                    {
                                        DataEntity entity = new DataEntity();
                                        entity.FieldName = specChild.Text;
                                        entity.FieldType = specChild.Tag.ToString().Trim();
                                        entity.FieldValue = strName;
                                        entity.FileldVersion = strVersion;
                                        specMainEntity.DataList.Add(entity);
                                    }
                                }
                                #endregion
                            }
                            #endregion
                        }
                    }
                    break;
                }

                specList.Add(specMainEntity);
                if (FilesNameList.Count>0)
                { 
                    //工序升版才更新附件
                    var specid = m_DAL.GetRDOID("spec", "specname", specName + "-" + item_ID, "spec" + "revision", strSpecVersion);
                    if (string.IsNullOrWhiteSpace(specid))
                    {
                        m_ObjectFileInfo.Add(new ObjectDocumentEntity() { ObjectName = specName + "-" + item_ID, ObjectRev = strSpecVersion, fileList = FilesNameList, type = "spec" });//存储文档信息
                    }
                    else
                    {
                        if (m_DAL.GetTableByFiledValue("objectdocinfo", "parentid", specid).Rows.Count == 0)//存在工序，但无附件时
                        {
                            m_ObjectFileInfo.Add(new ObjectDocumentEntity() { ObjectName = specName + "-" + item_ID, ObjectRev = strSpecVersion, fileList = FilesNameList, type = "spec" });//存储文档信息
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 创建文档附件 Yangsj 2017-10-30 
        /// add:Wangjh 弃用20211101
        /// </summary>
        /// <returns></returns>
        private string CreateDocumentSet(List<string> FilesNameList)
        {
            string DocumentSetName = string.Format("DS-{0}",
                                    DateTime.Now.ToString("yyyyMMddHHmmssffff"));

            Dictionary<string, string> NameAndRev = new Dictionary<string, string>();
            string strAccessPath = m_AccessoriesPath;
            if (!string.IsNullOrWhiteSpace(m_ProcessNo))
                strAccessPath += @"\" + m_ProcessNo;
            if (!Directory.Exists(strAccessPath))
                return string.Empty;
            OutInfoEntity infoEntity;

            for (int k = 0; k < FilesNameList.Count; k++)
            {
                if (!File.Exists(strAccessPath + "\\" + FilesNameList[k]))
                {
                    Log.WriteLog("未找到文件", 0, FilesNameList[k] + "未找到,跳过处理！");
                    Log.WriteOrcale("PDMTOMES_WorkFlowDocument" + "@^" + "未找到文件" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库
                    continue;
                }
                string DocumentName = string.Format("{0}-{1}",
                    Path.GetFileNameWithoutExtension(FilesNameList[k]),
                    DateTime.Now.ToString("yyyyMMddHHmmssffff"));

                #region 赋值
                SyncParameterEntity mainEntity = new SyncParameterEntity();

                mainEntity.OperationKind = "New";
                mainEntity.ServiceKey = "Document";
                mainEntity.DataList = new List<DataEntity>();

                DataEntity entity = new DataEntity();
                entity.FieldName = "Name";
                entity.FieldType = "dataField";
                entity.FieldValue = DocumentName;
                mainEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "Revision";
                entity.FieldType = "dataField";
                entity.FieldValue = "1";
                mainEntity.DataList.Add(entity);

                string strAA = m_TempPath + m_Assistant.uniqName();

                if (!Directory.Exists(strAA))
                    Directory.CreateDirectory(strAA);

                File.Move(strAccessPath + "\\" + FilesNameList[k], strAA + "\\" + FilesNameList[k]);

                //   strAA = strAA.Replace(m_TempPath, "http://localhost/InSiteWebApplication/Doc/");
                entity = new DataEntity();
                entity.FieldName = "Identifier";
                entity.FieldType = "dataField";
                entity.FieldValue = strAA + "\\" + FilesNameList[k];
                mainEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "FileLocation";
                entity.FieldType = "dataField";
                entity.FieldValue = strAA;
                mainEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "Status";
                entity.FieldType = "dataField";
                entity.FieldValue = "1";
                mainEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "FileName";
                entity.FieldType = "dataField";
                entity.FieldValue = FilesNameList[k];
                mainEntity.DataList.Add(entity);

                entity = new DataEntity();
                entity.FieldName = "UploadFile";
                entity.FieldType = "dataField";
                entity.FieldValue = "true";
                mainEntity.DataList.Add(entity);
                #endregion

                DataSet tmpSet = m_DAL.GetDocumentInfo(FilesNameList[k], "1");
                if (tmpSet.Tables[0].Rows.Count == 0)
                {
                    infoEntity = new OutInfoEntity();
                    m_excAPI.CreateDocument(mainEntity, ref infoEntity);
                    if (infoEntity.OutFlag == 1)
                    {
                        NameAndRev.Add(DocumentName, "1");
                        Log.WriteOrcale("PDMTOMES_WorkFLow" + infoEntity.StrServicekey + "@^" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                    }
                    else if (infoEntity.OutFlag == 2)
                    {
                        Log.WriteOrcale("PDMTOMES_WorkFLow" + infoEntity.StrServicekey + "@^" + "Document创建失败:" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                    }
                }
            }

            infoEntity = new OutInfoEntity();
            m_excAPI.CreateDocumentSet(DocumentSetName, NameAndRev, ref infoEntity);
            if (Directory.GetFiles(strAccessPath).Length == 0)
                Directory.Delete(strAccessPath);
            if (infoEntity.OutFlag == 1)
            {
                Log.WriteOrcale("PDMTOMES_WorkFLow" + infoEntity.StrServicekey + "@^" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                return DocumentSetName;
            }
            else
            {
                Log.WriteOrcale("PDMTOMES_WorkFLow" + infoEntity.StrServicekey + "@^" + "DocumentSet创建失败:" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   

                return string.Empty;
            }
        }

        private string ProcessNDOEntity(string strTable, string strName, string strValue)
        {
            bool isExist = false;

            if (strTable.ToLower() == "factory")
            {
                string strfactoryname = m_DAL.GetFacorybyCode(strValue);
                if (strfactoryname != strValue)
                {
                    return strfactoryname;
                }
                else {
                    return strValue;
                }
            }

            DataSet ds = m_DAL.GetNDOTable(strTable, strName, strValue);
            if (ds.Tables[0].Rows.Count > 0)
            {
                isExist = true;
            }

            if (!isExist)
            {
                OutInfoEntity infoEntity = new OutInfoEntity();
                SyncParameterEntity tmpEntity = new SyncParameterEntity();
                tmpEntity.DataList.Add(new DataEntity("Name", "dataField", strValue, ""));
                if (strTable.Equals("Operation"))
                {
                    tmpEntity.DataList.Add(new DataEntity("ThruputReportingLevel", "namedObjectField", "Lot", ""));
                }
                m_excAPI.CreateNDOEntity(strTable, tmpEntity, ref infoEntity);
                m_OutParameterObjectList.Add(infoEntity);
                if (infoEntity.OutFlag == 2)//add:Wangjh 2017-9-15 
                {
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + strTable + "创建失败:" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                }
                else
                {
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + strTable + "创建成功" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                }
            }
            return string.Empty;
        }
        #endregion
        /// <summary>
        /// 更新件号信息
        /// </summary>
        /// <param name="workFlowName"></param>
        /// <param name="workFlowVersion"></param>
        /// <param name="isTempFlow"></param>
        private void ChangeProductForWorkFlow(string workFlowName, string workFlowVersion, bool isTempFlow, string strFactory)
        {
            if (string.IsNullOrEmpty(m_strWorkFlowForProduct.Trim()))
            {
                return;
            }
            SyncParameterEntity productEntity = new SyncParameterEntity();

            productEntity.DataList = new List<DataEntity>();

            m_DAL.SaveProductWorkflowMapping(workFlowName, workFlowVersion, m_strWorkFlowForProduct, m_strWorkFlowForProductVer,m_CreateSubWorkflow );

            ///更新组别件工艺,叶片锻件工艺,存储ProductWorkflowMapping
            ///叶片分厂的锻件erp给订单时按materialcode作为name复制了一份product，此时更新复制的那一份也要更新 add:Wangjh 20211014
            DataTable dt = m_DAL.GetProductZBJ(m_strWorkFlowForProduct, m_strWorkFlowForProductVer);
            DataTable MDJDt = m_DAL.GetMDJERPProduct(m_strWorkFlowForProduct);
            foreach (DataRow dr in dt.Rows)
            {
                m_DAL.SaveProductWorkflowMapping(workFlowName, workFlowVersion, dr["productname"].ToString(), dr["productrevision"].ToString(), m_CreateSubWorkflow);
            }
            if (MDJDt.Rows.Count > 0)
            {
                m_DAL.SaveProductWorkflowMapping(workFlowName, workFlowVersion, MDJDt.Rows[0]["productname"].ToString(), MDJDt.Rows[0]["productrevision"].ToString(), m_CreateSubWorkflow);
            }
            //

            DataSet tmpSet1 = m_DAL.GetProductByVersion(m_strWorkFlowForProduct, m_strWorkFlowForProductVer);
            if (tmpSet1.Tables[0].Rows.Count > 0)
            {
                DataTable allProduct = m_DAL.GetAllProductByWorkflowAndProductName(m_strWorkFlowForProduct, workFlowName, workFlowVersion);
                DataView dv = allProduct.DefaultView;
                dv.RowFilter = "workflowtype2<>'临时工艺'";
                DataTable ZSdt = dv.ToTable();
                if (isTempFlow)
                {//临时工艺对应件号有工艺情况下，不更新 
                    //if (!tmpSet1.Tables[0].Rows[0].IsNull("WorkflowID"))  //注释 modify by longb 2025-06-05
                        //return;
                 //件号同时存在【正式、临时工艺】，最新的临时工艺不更新其他件号默认工艺
                    if (ZSdt.Rows.Count > 0) 
                        return;
                }
                else { allProduct = ZSdt; }
                ///更新组别件工艺
                productEntity.DataList.Add(new DataEntity("Workflow", "revisionedObjectField", workFlowName, workFlowVersion));

                OutInfoEntity infoEntity = new OutInfoEntity();
                m_excAPI.UpdateRDOEntity("Product", m_strWorkFlowForProduct, m_strWorkFlowForProductVer, productEntity, ref infoEntity);

                OutParameterObjectList.Add(infoEntity);

                if (infoEntity.OutFlag == 1)//add:Wangjh 2017-9-15 
                {
                    //获取productId
                    if (m_ProcessPlant == "603") {
                        string productId = string.Empty;
                        string workflowId = string.Empty;
                        productId = m_DAL.GetRDOID("Product", "ProductName", m_strWorkFlowForProduct, "ProductRevision", m_strWorkFlowForProductVer);
                        workflowId = m_DAL.GetRDOID("Workflow", "WorkflowName", workFlowName, "WorkflowRevision", workFlowVersion);
                        if (string.IsNullOrWhiteSpace(productId) == false && string.IsNullOrWhiteSpace(workflowId) == false)
                        {
                            m_DAL.UpdateTableFiledValue("workflow", workflowId, "productId", productId);
                        }
                    }
                    
                    ///子工艺件号关联
                    //if (m_CreateSubWorkflow)
                    //{
                    //    Dictionary<string, string> para = new Dictionary<string, string>();
                    //    para.Add("SubProduct", m_strWorkFlowForProduct);
                    //    para.Add("SubProductRev", m_strWorkFlowForProductVer);
                    //    para.Add("SubWorkflow", workFlowName);
                    //    para.Add("SubWorkflowRev", workFlowVersion);
                    //    para.Add("Factory", strFactory);
                    //    m_DAL.SaveProductSubProdcut(para);
                    //}

                    //更新叶片锻件工艺，API
                    //if (m_ProcessPlant == "608") {
                    if (MDJDt.Rows.Count > 0)
                    {
                        if (MDJDt.Select("productrevision='" + m_strWorkFlowForProductVer + "'").Length > 0)
                        {
                            m_excAPI.UpdateRDOEntity("Product", MDJDt.Rows[0]["productname"].ToString(), m_strWorkFlowForProductVer, productEntity, ref infoEntity);

                        }
                    }
                    //}
                    //

                    //更新组别件工艺,API
                    foreach (DataRow dr in dt.Rows)
                    {
                        m_excAPI.UpdateRDOEntity("Product", dr["productname"].ToString(), dr["productrevision"].ToString(), productEntity, ref infoEntity);
                    }
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                    //根据件号、工艺及其版本--查询其他版本所有的件号数据(更新所有的默认版本到最新版本) add by longb 2025-06-05
                    foreach (DataRow dr in allProduct.Rows)
                    {
                        m_excAPI.UpdateRDOEntity("Product", dr["productname"].ToString(), dr["productrevision"].ToString(), productEntity, ref infoEntity);
                    }
                }
                else if (infoEntity.OutFlag == 2)
                {
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + "Product修改失败:" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                }
            }
        }

        private void LoadWorkFlow()
        {
            string workFlowName = "";
            string workFlowVersion = "";
            string strResourceWorkFlowName = "";
            TreeNode workflownode = new TreeNode();
            foreach (TreeNode node in trvMes.Nodes)
            {
                if (node.Text == "WorkFlow")
                {
                    workflownode = node;
                    break;
                }
            }
            foreach (TreeNode wChildNode in workflownode.Nodes)  //workFlow下面业务数据处理
            {
                string strResourceValue = "";
                string strValue = "";
                if (wChildNode.Text == "Name")
                {
                    workFlowName = m_Assistant.GetMappingValue(wChildNode, trvEnterprise, ref strResourceValue);
                    strResourceWorkFlowName = strResourceValue;
                }
                else if (wChildNode.Text == "Revision")
                {
                    strValue = m_Assistant.GetMappingValue(wChildNode, trvEnterprise, ref strResourceValue);
                    if (strValue.Trim() == "")
                        workFlowVersion = "1";
                    else
                        workFlowVersion = strValue;
                }
                string qty="";//工装在制数量
                if (wChildNode.Text == "qty" && m_ProcessPlant == m_gzPlant) 
                {
                    qty = m_Assistant.GetMappingValue(wChildNode, trvEnterprise, ref qty);
                    if (qty.Trim() == "")
                    {
                        Log.WriteLog("工装工艺XML节点ly2initialdrawno数量为空，工艺无法创建", 1, "workFlow创建,数据文件" + m_DataFilePath);
                        Log.WriteOrcale("PDMTOMES_WorkFlow" + "@^" + "工装工艺XML节点ly2initialdrawno数量为空，工艺无法创建" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);
                        return;
                    }
                }

                string taskno = "";//工装任务号
                if (wChildNode.Text == "taskno" && m_ProcessPlant == m_gzPlant)
                {
                    taskno = m_Assistant.GetMappingValue(wChildNode, trvEnterprise, ref taskno);
                    if (taskno.Trim() == "")
                    {
                        Log.WriteLog("工装工艺XML节点ly2taskno任务号为空，工艺无法创建", 1, "workFlow创建,数据文件" + m_DataFilePath);
                        Log.WriteOrcale("PDMTOMES_WorkFlow" + "@^" + "工装工艺XML节点ly2taskno任务号为空，工艺无法创建" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);
                        return;
                    }
                }

                string bjqty = "";//工装备件数量
                if (wChildNode.Text == "bjqty" && m_ProcessPlant == m_gzPlant)
                {
                    bjqty = m_Assistant.GetMappingValue(wChildNode, trvEnterprise, ref bjqty);
                    if (bjqty.Trim() == "")
                    {
                        Log.WriteLog("工装工艺XML节点ly2bjqty备件数量为空，工艺无法创建", 1, "workFlow创建,数据文件" + m_DataFilePath);
                        Log.WriteOrcale("PDMTOMES_WorkFlow" + "@^" + "工装工艺XML节点ly2bjqty备件数量为空，工艺无法创建" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);
                        return;
                    }
                }

                string workcenterName = "";//工装工艺工区
                if (wChildNode.Text == "Workcenter" && m_ProcessPlant == m_gzPlant)
                {
                    workcenterName = m_Assistant.GetMappingValue(wChildNode, trvEnterprise, ref workcenterName);
                    var existWorkCenter = m_DAL.IsExistWorkCenter(m_gzPlant, workcenterName);
                    if (workcenterName.Trim() == "" || !existWorkCenter)
                    {
                        Log.WriteLog("工装工艺XML节点ly2Preparationdocuments值"+(string.IsNullOrWhiteSpace(workcenterName)?"为空":"【" + workcenterName + "】在MES端无数据")+"，工艺无法创建", 1, "workFlow创建,数据文件" + m_DataFilePath);
                        Log.WriteOrcale("PDMTOMES_WorkFlow" + "@^" + "工装工艺XML节点ly2Preparationdocuments值" + (string.IsNullOrWhiteSpace(workcenterName) ? "为空" : "【" + workcenterName + "】在MES端无数据") + "，工艺无法创建" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);
                        return;
                    }
                }

            }

            if (strResourceWorkFlowName.Trim() == "")
            {
                Log.WriteLog("未找到workFlow名称和版本，无法创建", 1, "workFlow创建,数据文件" + m_DataFilePath);
                Log.WriteOrcale("PDMTOMES_WorkFlow" + "@^" + "未找到workFlow名称和版本，无法创建" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库
                return;
            }

            List<DataEntity> specList = new List<DataEntity>();
            List<DataEntity> stepList = new List<DataEntity>();

            SyncParameterEntity mainEntity = new SyncParameterEntity();

            GetWorkFlowData(ref specList, ref stepList, ref mainEntity);
            if (stepList.Count == 0)
            {
                Log.WriteOrcale("PDMTOMES_Workflow"  + "@^" + "xml未找到工序，不创建工艺规程" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                return;
            }

            //foreach (DataEntity de in specList)
            //{
            //    if (de.FieldValue.ToString() == "空子工艺" && de.FileldVersion == "00")
            //    {
            //        Log.WriteOrcale("PDMTOMES_MachineMfgWorkFlow@^主工序对应子工艺没有指定分厂@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库    
            //        return;
            //    }
            //    if (de.IndexNo == specList.Count - 1 && de.FieldName == "SubWorkflow" && de.SpecFactoryCode != m_ProcessPlant)//add:Wangjh 2018/10/8增加分厂判断
            //    {
            //        Log.WriteOrcale("PDMTOMES_MachineMfgWorkFlow@^最后一道工序不能是需要转工的子工艺@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库    
            //        return;
            //    }
            //}

            DataTable wfdt = m_DAL.GetRDOByAllVersion("WorkFlow", "WorkFlowName", workFlowName);

            OutInfoEntity infoEntity = new OutInfoEntity();
            if (wfdt.Rows.Count > 0)
            {
                if (wfdt.Select(string.Format("WorkFlowName='{0}' and WorkFlowRevision='{1}'", workFlowName, workFlowVersion)).Length == 0)
                {
                    string oldVersion = wfdt.Select("WorkFlowID=Revofrcdid")[0]["WorkFlowRevision"].ToString();
                    if (oldVersion.Trim() != "")
                    {
                        m_excAPI.CreateNewWorkFlowRevision(oldVersion, workFlowName, mainEntity, stepList, specList, ref  infoEntity);
                        m_OutParameterObjectList.Add(infoEntity);

                        if (infoEntity.OutFlag == 1)//add:Wangjh 2017-9-15 
                        {
                            //继承上一工艺的工序班组或工区或工时信息或主子工序映射信息
                            //inheritLastWorkflowSomeInfo(infoEntity, workFlowName);
                        }
                        else if (infoEntity.OutFlag == 2)
                        {
                            infoEntity.StrInfo = "workFlow版本添加失败:" + infoEntity.StrInfo;
                        }
                    }
                    else
                    {
                        infoEntity.StrInfo = "workFlow版本添加失败:" + workFlowName + "未找到默认版本，无法创建" + infoEntity.StrInfo;

                        Log.WriteLog(infoEntity.StrInfo, 1, "workFlow创建,数据文件" + m_DataFilePath);
                        Log.WriteOrcale("PDMTOMES_WorkFlow" + "@^" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库
                        return;
                    }
                }
                else
                {
                    infoEntity.StrInfo = "workFlow版本添加失败:" + workFlowName + "." + workFlowVersion + "已经存在！" + infoEntity.StrInfo;
                    Log.WriteLog(infoEntity.StrInfo, 0, "workFlow创建");
                }
            }
            else
            {
                m_excAPI.CreateNewWorkFlow(mainEntity, stepList, specList, ref infoEntity);
                m_OutParameterObjectList.Add(infoEntity);
                if (infoEntity.OutFlag == 2)
                {
                    infoEntity.StrInfo = "workFlow创建失败:" + infoEntity.StrInfo;
                }
            }
            if (m_CreateSubWorkflow )
                Log.WriteOrcale("PDMTOMES_Workflow" + infoEntity.StrServicekey + "@^"+"子工艺," + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
            else
                Log.WriteOrcale("PDMTOMES_Workflow" + infoEntity.StrServicekey + "@^" + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   


            DataTable stepDt = m_DAL.GetWorkflowStepByWfNameAndRev(workFlowName, workFlowVersion).Tables [0];//获取工艺的所有工序信息
           
            DataTable faStepDt = new DataTable();
            if (m_FaProcessNo != "" && m_FaProcessNo != "")//推送xml有父工艺
            {
                faStepDt = m_DAL.GetWorkflowStepByWfNameAndRev("WF-" + m_FaProcessNo, m_FaProcessRev).Tables[0];//获取父工艺的所有工序信息
            }
            //子工艺情况，继承之前拆分的子工艺维护的工区班组信息 add:Wangjh 20180926
            inheritSplitSubWorkflowSomeInfo(stepDt,infoEntity, workFlowName, workFlowVersion, strResourceWorkFlowName);
            //
            // add:Wangjh 20181207
            XmlNodeList meopNodes = m_myXml.SelectNodes("/Root/WorkFlow/MEOPs/MEOP");

            foreach (DataEntity spec in specList)
            {
                string workflowstepName = spec.FieldValue.ToString().Replace(m_PdmProductName + "-", null);
                workflowstepName=workflowstepName.Replace ("-"+spec.Item_ID,null );
                DataRow[] drs = stepDt.Select("workflowstepname='" + workflowstepName + "'"); //筛选对应的工序
                if (drs.Length == 0)
                    continue;
                if (spec.IsSubStep == true)//含有子工艺的工序做特殊标识
                {
                    m_DAL.UpdateTableFiledValue("workflowstep", drs[0]["workflowstepid"].ToString(), "wipmsglabel", "子工艺");
                }
                else {
                    m_DAL.UpdateTableFiledValue("workflowstep", drs[0]["workflowstepid"].ToString(), "wipmsglabel", "");
                }
                if (spec.FaMeopNo != "")//有父工序,增加父子工序映射信息
                {
                     if(faStepDt .Rows.Count ==0)
                         continue ;
                     DataRow[] faDrs = faStepDt.Select("specno='" + spec.FaMeopNo + "'"); //筛选对应的父工序
                     if (faDrs.Length == 0)
                         continue;
                     m_DAL.SaveStepSubStep(faDrs[0]["workflowid"].ToString(), drs[0]["workflowid"].ToString(), faDrs[0]["workflowstepid"].ToString(), drs[0]["workflowstepid"].ToString());
                }
                //更新workflowstep上的属性，WorkcenterCode
                Dictionary<string, string> filedValues = new Dictionary<string, string>();
                if (meopNodes.Item(spec.IndexNo).SelectSingleNode("work_center_code") != null) {
                    filedValues.Add("workcentercode", meopNodes.Item(spec.IndexNo).SelectSingleNode("work_center_code").InnerText);
                }
                m_DAL.UpdateTableFiledsValues("workflowstep", drs[0]["workflowstepid"].ToString(), filedValues);
            }
            //

            //继承前版本信息 add:wangjh 20240710
            if (infoEntity.OutFlag == 1)
            {
                inheritLastWorkflowSomeInfo(infoEntity, workFlowName);            
            }



            bool IsTempFlow = false;
            string factory = "";
            for (int i = 0; i < mainEntity.DataList.Count; i++)
            {
                DataEntity tmpEntity = mainEntity.DataList[i];
                if (tmpEntity.FieldName == "WorkFlowType2")
                {
                    if (tmpEntity.FieldValue.ToString().Trim() == "临时工艺")
                        IsTempFlow = true;
                }
                else if (tmpEntity.FieldName == "Factory")
                {
                    factory = tmpEntity.FieldValue.ToString().Trim();
                }
            }
           //Debugger.Launch();
            ChangeProductForWorkFlow(workFlowName, workFlowVersion, IsTempFlow, factory);
            LoadUrls(workFlowName, workFlowVersion);
        }

        #region 导入workflow附件
        /// <summary>
        /// 
        /// </summary>
        private void LoadWorkFlowDocumentSet()
        {
            List<string> FilesNameList = new List<string>();
            foreach (TreeNode node in trvMes.Nodes)
            {
                if (node.Text == "WorkFlow")
                {
                    foreach (TreeNode wChildNode in node.Nodes)  //workFlow下面业务数
                    {
                        if (wChildNode.Text == "Name")
                        {
                            string strResourceValue = "";
                            string strValue = m_Assistant.GetMappingValue(wChildNode, trvEnterprise, ref strResourceValue);
                            m_workflowName = strValue;
                        }

                        if (wChildNode.Text == "Revision")
                        {
                            string strResourceValue = "";
                            string strValue = m_Assistant.GetMappingValue(wChildNode, trvEnterprise, ref strResourceValue);
                            m_workflowRev = strValue;
                        }

                        if (wChildNode.Text == "Documentset")
                        {
                            //foreach (TreeNode item in trvEnterprise.Nodes[trvEnterprise.Nodes.Count - 1].Nodes[1].Nodes)
                            //{
                            //    GetDocumentList(FilesNameList, item);
                            //}
                            GetDocumentList(FilesNameList, m_myXml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess"));
                        }
                    }
                }
            }
            if (FilesNameList.Count > 0) {
                //文档对象赋值    
                var workflowid = m_DAL.GetRDOID("workflow", "workflowname", m_workflowName, "workflow" + "revision", m_workflowRev);
                if (string.IsNullOrWhiteSpace(workflowid)) //工艺升版才更新
                {
                    m_ObjectFileInfo.Add(new ObjectDocumentEntity() { ObjectName = m_workflowName, ObjectRev = m_workflowRev, fileList = FilesNameList, type = "workflow" });//存储文档信息
                }
                else {
                    if (m_DAL.GetTableByFiledValue("objectdocinfo", "parentid", workflowid).Rows.Count == 0)//存在工艺规程，但无附件时
                    {
                        m_ObjectFileInfo.Add(new ObjectDocumentEntity() { ObjectName = m_workflowName, ObjectRev = m_workflowRev, fileList = FilesNameList, type = "workflow" });//存储文档信息  
                    }
                }
            }
            

            //update:wangjh 20211101 注释
            //if (FilesNameList.Count == 0)
            //{
            //    m_StrWorkFlowDocumentName = "";
            //    return;
            //}


            //m_StrWorkFlowDocumentName = CreateDocumentSet(FilesNameList);

        }
        #endregion

        private void GetDocumentList(List<string> FilesNameList, TreeNode item)
        {
            foreach (TreeNode docNode in item.Nodes)
            {
                if (docNode.Text == "Documents")
                {
                    foreach (TreeNode fileNode in docNode.Nodes)
                    {
                        FilesNameList.Add(fileNode.Tag.ToString());
                    }
                }
                else
                {
                    GetDocumentList(FilesNameList, docNode);
                }
            }
        }

        #region "获取附件文档信息 add:Wangjh 20220901"
        private void GetDocumentList(List<string> FilesNameList, XmlNode  item)
        {
            if (item == null)
                return;
            if (item.SelectSingleNode("Documents") == null)
                return;
            foreach (XmlNode file in item.SelectSingleNode("Documents").ChildNodes)
            {
                FilesNameList.Add(file.InnerText );
            }
        }
        #endregion

        #region  子工艺处理

        /// <summary>
        /// 子工艺处理,true没有子工艺，有子工艺,此方法只创建子零件号
        /// </summary>
        private bool LoadSubWorkflowByMEOP()
        {

            XmlDocument myxml = new XmlDocument();
            myxml.Load(m_DataFilePath);
            XmlNode stu = myxml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess");
            if (stu == null)
                return true;
             m_FaProcessNo = stu.SelectSingleNode("ly2Mprocess_no").InnerText;//父工艺
            if (string.IsNullOrEmpty(m_FaProcessNo))
                return true;
             m_FaProcessRev = stu.SelectSingleNode("ly2process_revID").InnerText;//父工艺版本
            if (string.IsNullOrEmpty(m_FaProcessRev))
                return true;


            string productName = "";
            //add:Wangjh 20180503 
            string[] productInfo = m_Assistant.GetProductName(m_DataFilePath);
            productName = productInfo[0];
            string productRev = productInfo[1]; ;//主零件号版本
            //
            //取第一个有子工艺的工序 add:Wangjh 20181207
            string firstFaOPNO = "";
            XmlNodeList faOPNOs = myxml.SelectNodes("/Root/WorkFlow/MEOPs/MEOP/ly2Mmeop_no");
            if (faOPNOs.Count == 0) {
                Log.WriteLog("此子工艺没有对应主工艺工序号", 1, "子零件号创建" + m_DataFilePath);
                Log.WriteOrcale("PDMTOMES_CreateSubProduct" + "@^" + "此子工艺没有对应主工艺工序号" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库  
                return false;
            }
            firstFaOPNO = faOPNOs[0].InnerText;
            //

            //stu = myxml.SelectSingleNode("/Root/WorkFlow/MEOPs");
            //DataTable meopdt = new DataTable();
            //meopdt.Columns.Add("OPType");
            //meopdt.Columns.Add("OPName");
            //meopdt.Columns.Add("SpecName");
            //meopdt.Columns.Add("SpecRev");
            //meopdt.Columns.Add("FaOPNO");
            //foreach (XmlNode node in stu.ChildNodes)
            //{
            //    if (node.Name != "MEOP")
            //        continue;
            //    DataRow dr = meopdt.NewRow();
            //    dr["OPName"] = string.Format("{0}-{1}",
            //           node.SelectSingleNode("ly2meop_no").InnerText.Trim(),
            //           node.SelectSingleNode("object_name").InnerText.Trim());
            //    dr["FaOPNO"] = node.SelectSingleNode("ly2Mmeop_no").InnerText.Trim();

            //    dr["OPType"] = "Spec";
            //    dr["SpecName"] = string.Format("{0}-{1}", productName, dr["OPName"]);
            //    dr["SpecRev"] = node.SelectSingleNode("item_revision_id").InnerText.Trim();

            //    meopdt.Rows.Add(dr);
            //}
           // FillSubWorkFlow(meopdt, strFaProcessNo, strFaProcessRev);
            CreateSubbWorkflowProduct(productName, productRev, m_FaProcessNo, m_FaProcessRev, firstFaOPNO);
            return false;
        }
        private void FillSubWorkFlow(DataTable meopdt, string strfaworkflow, string strfaworkflowrev)
        {
            SyncParameterEntity mainEntity = new SyncParameterEntity();
            GetWorkFlowData(ref mainEntity);
            DataTable opnodt = meopdt.DefaultView.ToTable(true, "FaOPNO");
            foreach (DataRow dr in opnodt.Rows)
            {
                if (string.IsNullOrEmpty(dr["FaOPNO"].ToString()))
                    continue;
                DataRow[] drs = meopdt.Select(string.Format("FaOPNO='{0}'", dr["FaOPNO"]));
                List<DataEntity> specList = new List<DataEntity>();
                List<DataEntity> stepList = new List<DataEntity>();
                string strWorkflowStepID = m_DAL.GetParentWorkflowStep(strfaworkflow, strfaworkflowrev, dr["FaOPNO"].ToString());
                if (string.IsNullOrWhiteSpace(strWorkflowStepID))
                {
                    Log.WriteOrcale("PDMTOMES_SubWorkFlow" + "@^" + "subworkFlow没有对应父工艺版本添加失败" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库       
                    continue;
                }
                string strSubWorkflowName = string.Format("{0}-{1}", strfaworkflow, dr["FaOPNO"]);//父工艺号-父工序号
                string strSubWorkflowRev = "";
                int intIntIndex = 0;
                foreach (DataRow _dr in drs)
                {
                    DataEntity specEntity = new DataEntity(_dr["OPType"].ToString(), "revisionedObjectField", _dr["SpecName"].ToString(), _dr["SpecRev"].ToString());
                    specEntity.IndexNo = intIntIndex;
                    specList.Add(specEntity);

                    DataEntity tmpEntity = new DataEntity("Step", "appendItem", _dr["OPName"].ToString(), "");
                    tmpEntity.IndexNo = intIntIndex;
                    stepList.Add(tmpEntity);
                    intIntIndex++;

                }
                foreach (DataEntity de in mainEntity.DataList)
                {
                    if (de.FieldName == "Name")
                    { de.FieldValue = strSubWorkflowName; }
                    else if (de.FieldName == "Revision")
                    { strSubWorkflowRev = de.FieldValue.ToString(); }
                    else
                        continue;
                }

                DataSet tmpSet = m_DAL.GetWorkflowInfo(strSubWorkflowName, strSubWorkflowRev);

                OutInfoEntity infoEntity = new OutInfoEntity();
                if (tmpSet.Tables[0].Rows.Count == 0)
                {
                    DataSet tmp1Set = m_DAL.GetWorkflowInfoByName(strSubWorkflowName);
                    if (tmp1Set.Tables[0].Rows.Count > 0)
                    {
                        string oldVersion = tmp1Set.Tables[0].Rows[0]["WORKFLOWREVISION"].ToString();
                        m_excAPI.CreateNewWorkFlowRevision(oldVersion, strSubWorkflowName, mainEntity, stepList, specList, ref  infoEntity);
                        m_OutParameterObjectList.Add(infoEntity);
                        if (infoEntity.OutFlag == 1)//add:Wangjh 2017-9-15 
                        {
                            //继承上一工艺的工序班组或工区或工时信息或主子工序映射信息
                            inheritLastWorkflowSomeInfo(infoEntity, strSubWorkflowName);
                        }
                        else if (infoEntity.OutFlag == 2)
                            infoEntity.StrInfo = "workFlow版本添加失败:" + infoEntity.StrInfo;
                    }
                    else
                    {
                        m_excAPI.CreateNewWorkFlow(mainEntity, stepList, specList, ref infoEntity);
                        m_OutParameterObjectList.Add(infoEntity);
                        if (infoEntity.OutFlag == 2)
                            infoEntity.StrInfo = "workFlow创建失败:" + infoEntity.StrInfo;
                    }
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" +"子工艺"+ infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   

                }
                DataSet ds = m_DAL.GetWorkflowInfo(strSubWorkflowName, strSubWorkflowRev);
                if (ds == null)
                    continue;
                if (ds.Tables[0].Rows.Count == 0)
                    continue;
                string strWorkflowID = ds.Tables[0].Rows[0]["workflowid"].ToString();
                m_DAL.UpdateStepWorkflowInfo(strWorkflowID, strWorkflowStepID);
                m_DAL.SaveProductWorkflowMapping(strSubWorkflowName, strSubWorkflowRev, m_strWorkFlowForProduct, m_strWorkFlowForProductVer);

            }
        }

        #endregion
        /// <summary>
        /// 获取上一版本子工艺信息
        /// </summary>
        private void GetSubWorkflowOldVersion(List<DataEntity> dataList, string stepname, out string subName, out string subREV)
        {
            string workflowname = "";
            foreach (DataEntity de in dataList)
            {
                if (de.FieldName == "Name")
                {
                    workflowname = de.FieldValue.ToString();
                    break;
                }
            }
            DataTable dt = m_DAL.GetStepSubWorkflow(workflowname, stepname);
            if (dt.Rows.Count > 0 && dt.Rows[0]["sname"].ToString().Contains ("空子工艺")==false )
            {
                subName = dt.Rows[0]["sname"].ToString();
                subREV = dt.Rows[0]["srev"].ToString();
            }
            else
                subREV = subName = "";
        }
        /// <summary>
        /// 继承上一工艺的工序班组或工区或工时信息或主子工序映射信息
        /// add:Wangjh 20180412
        /// </summary>
        private void inheritLastWorkflowSomeInfo(OutInfoEntity infoEntity, string workFlowName)
        {
            //添加上一个版本的一些信息 add:Wangjh 20180201
            string strfactory = m_DAL.GetFacorybyCode(m_ProcessPlant);
            DataTable workflowDt = m_DAL.GetAllWorkflow(strfactory, workFlowName);
            if (workflowDt.Rows.Count > 1)//至少2个版本包括当前版本
            {
                string lastWorkflowID = workflowDt.Rows[1]["workflowid"].ToString();//上一个版本的工艺ID
                DataTable lastStepDt = m_DAL.GetWorkflowStepTime(lastWorkflowID);//上一个版本的工序信息
                DataTable origLastStepDt = lastStepDt.Copy();//复制一份，防止更新工区班组时值变化
                string newWorkflowID = workflowDt.Rows[0]["workflowid"].ToString();//刚添加最新版本的
                //继承工艺上的一些信息 add:wangjh 20250307
                m_DAL.updateWorkflowFromOldWf(newWorkflowID, lastWorkflowID);
                DataTable newStepDt = m_DAL.GetWorkflowStepTime(newWorkflowID);//最新版本的工序信息 ;
                //添加上一个版本的工时或班组或工区数据 add:Wangjh 20180201                              
                DataRow[] HaveStepTimeDrs = lastStepDt.Select(@"DURATIONPERUNIT is not null OR WORKCENTERID IS NOT NULL OR TEAMID IS NOT NULL OR manhours IS NOT NULL 
                or makecycle is not null or shipcycle is not null or commicycle is not null or chargingqty is not null");//筛选有工时或有工区或有班组或有商品工时的
                if (HaveStepTimeDrs.Length > 0)//上一个版本有工时或有工区或有班组
                {
                    foreach (DataRow dr in HaveStepTimeDrs)
                    {
                        // DataRow[] temDrs = newStepDt.Select(string.Format("SEQUENCE={0} and SPECNO={1}", dr["SEQUENCE"], dr["SPECNO"]));//筛选新版本对应的工序  最开始
                        //DataRow[] temDrs = newStepDt.Select(string.Format(" SPECNO={0}", dr["SPECNO"]));//筛选新版本对应的工序  中间
                        DataRow[] temDrs = newStepDt.Select(string.Format(" WORKFLOWSTEPNAME='{0}'", dr["WORKFLOWSTEPNAME"].ToString()));//筛选新版本对应的工序 最后 ,周文杰提出的要workflowstepname完全一致
                        if (temDrs.Length == 0)
                            continue;
                        dr["WORKFLOWSTEPID"] = temDrs[0]["WORKFLOWSTEPID"].ToString();
                        if (m_DAL.UpdateStepTimeInfo(dr) == false)
                        {
                            continue;
                        }
                        Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + "最新版" + workFlowName + "工序号" + dr["SPECNO"].ToString() + "工时或工区或班组或商品工时同步成功" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库 
                    }
                }
                //继承上一个版本的主子工序映射信息 add:Wangjh 20181207 
                //DataTable stepSubStepDt = m_DAL.GetTableByFiledValue("stepsubstep", "workflowid", lastWorkflowID);//根据主工艺查询映射信息
                //if (stepSubStepDt.Rows.Count > 0)
                //{
                //    foreach (DataRow dr in stepSubStepDt.Rows)
                //    {
                //        DataRow[] lastSubSteps = origLastStepDt.Select("workflowstepid='" + dr["workflowstepid"].ToString() + "'");//上个版本对应的工序信息
                //        if (lastSubSteps.Length == 0)
                //            continue;
                //        DataRow[] nowSteps = newStepDt.Select("WORKFLOWSTEPNAME='" + lastSubSteps[0]["WORKFLOWSTEPNAME"].ToString() + "'");//对应当前版的工艺
                //        if (nowSteps.Length == 0)
                //            continue;
                //        m_DAL.SaveStepSubStep(newWorkflowID, dr["sonworkflowid"].ToString(), nowSteps[0]["workflowstepid"].ToString(), dr["sonworkflowstepid"].ToString());

                //    }
                //}

                //子工艺继承逻辑更改，更改为继承不止上一个版本，每一个序继承最近含有子工艺的版本 update:Wangjh 20240708
                DataRow[] subSteps = newStepDt.Select("wipmsglabel='子工艺'");
                if (subSteps.Length > 0)
                {
                    foreach (DataRow subStep in subSteps)
                    {
                        DataTable lastestSubStep = m_DAL.GetSubWorkflowStep(workFlowName, subStep["workflowstepname"].ToString());
                        if (lastestSubStep.Rows.Count == 0)
                            continue;
                        if (lastestSubStep.Rows[0]["workflowstepid"].ToString() == subStep["workflowstepid"].ToString())//当前序本身有子工艺信息，跳过
                        {
                            continue;
                        }
                        DataRow[] newSubSteps = lastestSubStep.Select("workflowstepid='" + lastestSubStep.Rows[0]["workflowstepid"].ToString() + "'");
                        foreach (DataRow newSubStep in newSubSteps) {

                            m_DAL.SaveStepSubStep(newWorkflowID, newSubStep["sonworkflowid"].ToString(), subStep["workflowstepid"].ToString(),
                                newSubStep["sonworkflowstepid"].ToString());

                            Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + "最新版" + workFlowName + "工序号" + subStep["SPECNO"].ToString() + "的子工序 " + newSubStep["sonworkflowstepid"].ToString()
                                + " 继承同步成功" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库 
                    
                        }
                    }
                }               

                //继承工序设备数据 add by longb 2023-07-21
                foreach (DataRow row in origLastStepDt.Rows) 
                {
                    DataRow[] temDrs = newStepDt.Select(string.Format(" WORKFLOWSTEPNAME='{0}'", row["WORKFLOWSTEPNAME"].ToString()));//筛选新版本对应的工序 最后 ,周文杰提出的要workflowstepname完全一致
                    if (temDrs.Length == 0)
                        continue;
                    m_DAL.CreateStepResourceData(row["specid"].ToString(), temDrs[0]["specid"].ToString());
                }

                //
            }
        }

        /// <summary>
        /// 继承之前被拆分过的子工艺的工序班组或工区或工时信息
        /// add:Wangjh 20180926
        /// </summary>
        /// <param name="infoEntity"></param>
        /// <param name="workFlowName"></param>
        /// <param name="workFlowVersion"></param>
        /// <param name="strResourceWorkFlowName"></param>
        private void inheritSplitSubWorkflowSomeInfo(DataTable stepDt,OutInfoEntity infoEntity, string workFlowName, string workFlowVersion, string strResourceWorkFlowName)
        {
            if (!m_CreateSubWorkflow)
                return;        
            if (stepDt != null && stepDt.Select("DURATIONPERUNIT is not null OR WORKCENTERID IS NOT NULL OR TEAMID IS NOT NULL OR manhours IS NOT NULL").Length == 0)//只继承之前拆分过且没有重新继承的子工艺 
            {
                DataSet ds2 = m_DAL.GetWorkcenterOrTeamByProcessNo(strResourceWorkFlowName);//含有工时或工区或班组或商品工时的工序
                if (ds2 == null)
                    return;
                foreach (DataRow dr in stepDt.Rows)
                {
                    DataRow[] temDr = ds2.Tables[0].Select("(DURATIONPERUNIT is not null OR WORKCENTERID IS NOT NULL OR TEAMID IS NOT NULL OR manhours IS NOT NULL) and workflowstepname='" + dr["workflowstepname"].ToString() + "'");
                    if (temDr.Length == 0)
                        continue;
                    temDr[0]["WORKFLOWSTEPID"] = dr["WORKFLOWSTEPID"];
                    if (m_DAL.UpdateStepTimeInfo(temDr[0]) == false)
                    {
                        continue;
                    }
                    Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + "最新版" + workFlowName + "工序号" + dr["SPECNO"].ToString() + "工时或工区或班组或商品工时同步成功(继承拆分过子工艺的)" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库 
                }
             
            }
        
        }

        /// <summary>
        /// 创建子工艺件号
        /// </summary>
        /// <param name="srcProduct"></param>
        /// <param name="srcRevision"></param>
        /// <param name="wfRevision"></param>
        /// <param name="opno"></param>
        private void CreateSubbWorkflowProduct(string srcProduct, string srcRevision, string wfName, string wfRevision, string opno)
        {
            m_CreateSubWorkflow = true;
            OutInfoEntity infoEntity = new OutInfoEntity();
            m_strWorkFlowForProduct = string.Format("{0}子工艺({1})", srcProduct, opno);
            m_strWorkFlowForProductVer = srcRevision;
            DataTable productDT = m_DAL.GetRDOByAllVersion("Product", "ProductName", m_strWorkFlowForProduct);//查询子零件号

            SyncParameterEntity mainEntity = new SyncParameterEntity();
            mainEntity.ServiceKey = "Product";
            mainEntity.DataList = new List<DataEntity>();
            mainEntity.DataList.Add(new DataEntity("Name", "dataField", m_strWorkFlowForProduct, string.Empty));
            mainEntity.DataList.Add(new DataEntity("Revision", "dataField", m_strWorkFlowForProductVer, string.Empty));
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("Product", srcProduct);
            para.Add("ProductRev", srcRevision);
            para.Add("SubProduct", m_strWorkFlowForProduct);
            para.Add("SubProductRev", m_strWorkFlowForProductVer);
            //para.Add("Workflow", "WF-" + wfName);
            //para.Add("WorkflowRev", wfRevision);

            if (productDT.Rows.Count == 0)
            {
                //Dictionary<Int32, SortedList<string, string>> pList = new Dictionary<int, SortedList<string, string>>();
                mainEntity.OperationKind = "SaveAs";
                mainEntity.DataList.Add(new DataEntity("ProductType", "namedObjectField", "子工艺虚拟件", string.Empty));
                mainEntity.DataList.Add(new DataEntity("WorkflowRoute", "dataField", srcProduct, string.Empty));
                mainEntity.DataList.Add(new DataEntity("Workflow", "revisionedObjectField", string.Empty, string.Empty));  
               // mainEntity.DataList.Add(new DataEntity("Substitutes", "revisionedObjectList", pList, string.Empty));
                m_excAPI.SaveAsEntity("Product", srcProduct, srcRevision, mainEntity, ref infoEntity);
                mainEntity.DataList.Clear();
                //SortedList<string, string> p = new SortedList<string, string>();
                //p.Add("Name", m_strWorkFlowForProduct);
                //p.Add("Revision", m_strWorkFlowForProductVer);
                //pList.Add(1, p);
                //mainEntity.DataList.Add(new DataEntity("Substitutes", "revisionedObjectList", pList, string.Empty));
                //m_excAPI.UpdateRDOEntity ("Product", srcProduct, srcRevision, mainEntity, ref infoEntity);
                m_DAL.SaveProductSubProdcut(para);
            }
            else
            {
                if (productDT.Select(string.Format("ProductName='{0}' and ProductRevision='{1}'", m_strWorkFlowForProduct, m_strWorkFlowForProductVer)).Length == 0)
                {
                    mainEntity.OperationKind = "SaveAsRev";
                    mainEntity.DataList.Add(new DataEntity("Description", "dataField", productDT.Rows[0]["Description"].ToString(), string.Empty));
                    mainEntity.DataList.Add(new DataEntity("ProductType", "namedObjectField", "子工艺虚拟件", string.Empty));
                    mainEntity.DataList.Add(new DataEntity("WorkflowRoute", "dataField", srcProduct, string.Empty));
                    mainEntity.DataList.Add(new DataEntity("Workflow", "revisionedObjectField", string.Empty, string.Empty));               
                    string oldRevision = productDT.Select("ProductID=Revofrcdid")[0]["ProductRevision"].ToString();
                    m_excAPI.CreateRDOEntityRevision("Product", m_strWorkFlowForProduct, oldRevision, mainEntity, ref infoEntity);//
                    m_DAL.SaveProductSubProdcut(para);
                }
            }

            if (infoEntity.OutFlag == 2)
                infoEntity.StrInfo = "Product子工艺虚拟件创建失败:" + infoEntity.StrInfo;

            Log.WriteOrcale("PDMTOMES_" + infoEntity.StrServicekey + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer+"," + infoEntity.StrInfo + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   

        }

        /// <summary>
        /// 存储pdm地址
        /// add:Wangjh 20181114
        /// </summary>
        private void LoadUrls(string workflowName,string workflowRev){
            XmlDocument myxml = new XmlDocument();
            myxml.Load(m_DataFilePath);
            //存储工艺url
            XmlNodeList urlNodes = myxml.SelectNodes("/Root/WorkFlow/MEProcesss/MEProcess/Urls/Url");
            string parentID = "";
            StandardDAL dal = new StandardDAL();
            if (urlNodes.Count > 0)
            {
                parentID = dal.GetRDOID("workflow", "workflowname", workflowName, "workflowrevision", workflowRev);
                foreach (XmlNode url in urlNodes)
                {
                    InsertOneUrl(url,parentID ,dal);
                }
            }
            //
            //存储工序url
            DataTable workflowStepDt = dal.GetWorkflowStepByWfNameAndRev(workflowName, workflowRev).Tables[0];
            if (workflowStepDt.Rows.Count == 0)
                return;
            XmlNodeList MEOPNodes = myxml.SelectNodes("/Root/WorkFlow/MEOPs/MEOP");
            foreach (XmlNode meopNode in MEOPNodes)
            {
                //存储工序url
                urlNodes = meopNode.SelectNodes("Urls/Url");
                if (urlNodes.Count > 0)
                {
                    string workflowstepName = meopNode.SelectSingleNode("ly2meop_no").InnerText + "-" + meopNode.SelectSingleNode("object_name").InnerText;
                    DataRow[] workflowstepIDs = workflowStepDt.Select("workflowstepname='" + workflowstepName + "'");
                    if (workflowstepIDs.Length == 0)//无此工序
                        continue;
                    parentID = workflowstepIDs[0]["workflowstepid"].ToString();
                    foreach (XmlNode url in urlNodes)
                    {
                        InsertOneUrl(url, parentID, dal);
                    }
                }
             }
             //
        }
        /// <summary>
        /// 存储每一个url
        /// add:Wangjh 20181114
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parentID"></param>
        /// <returns></returns>
        void InsertOneUrl(XmlNode url,string parentID,StandardDAL dal) {
            Dictionary<string, string> para = new Dictionary<string, string>();
            para["ParentID"] = parentID;
            string name = "", link = "";
            foreach (XmlNode urlItem in url.ChildNodes)
            {
                if (urlItem.Name == "name")
                    name = urlItem.InnerText;
                if (urlItem.Name == "link")
                    link = urlItem.InnerText;
                if (name != "" && link != "")
                {
                    para["FileName"] = name;
                    para["Link"] = link;
                    dal .InsertUrl(para);
                }
            }
        }

        #region 创建完工艺规程后，再次循环工序处理一些信息 add:Wangjh 20221129
        /// <summary>
        /// 循环处理一些工序其他信息
        /// </summary>
        void DealMeopSomeInfo() {
            XmlNode meops = m_myXml.SelectSingleNode("/Root/WorkFlow/MEOPs");
            DataTable wsDT = m_DAL.GetWorkflowStepByWfNameAndRev(m_workflowName, m_workflowRev).Tables[0];
            string workflowid = wsDT.Rows.Count > 0 ? wsDT.Rows[0]["WORKFLOWID"].ToString () : "";
            if (string.IsNullOrWhiteSpace(workflowid)) {
                return;
            }
            foreach (XmlNode nod in meops.ChildNodes)
            {
                if (nod.Name != "MEOP")
                    continue;
                var specVersion = nod.SelectSingleNode("item_revision_id").InnerText;
                var specNo = nod.SelectSingleNode("ly2meop_no").InnerText;
                //var specName = m_PdmProductName + "-" + nod.SelectSingleNode("ly2meop_no").InnerText + "-" + nod.SelectSingleNode("object_name").InnerText + "-" + nod.SelectSingleNode("item_id").InnerText;
                var opdesc = nod.SelectSingleNode("object_name").InnerText;
                var wsDT2=wsDT.Select(" WORKFLOWSTEPNAME='" + specNo.Trim () + "-" + opdesc.Trim () + "'");
                var specid =wsDT2.Length>0?wsDT2[0]["specid"].ToString():"";
                var stepid = wsDT2.Length>0?wsDT2[0]["workflowstepid"].ToString():"";
                if (string.IsNullOrWhiteSpace(specid) && string.IsNullOrWhiteSpace(stepid)) { continue; }
                foreach (XmlNode meopNode in nod.ChildNodes)
                { 
                    //特殊过程解析
                    try
                    {
                        DataTable SpecialCourseSpecReport = GetDatatableStruct("");//主表
                        DataTable SpecialCourseSpecParas = GetDatatableStruct("1");//细表
                        SaveMeopSpecialProcess(SpecialCourseSpecReport, SpecialCourseSpecParas, meopNode, workflowid, specid, stepid);
                        //释放

                    }
                    catch (Exception ex)
                    {
                        Log.WriteLog("工序：" + specNo + ex.StackTrace, 1, "特殊过程处理");
                        Log.WriteOrcaleError("PDMTOMES_Workflow" + "@^" + "特殊过程处理出错,工序：" + specNo + ex.Message +ex.StackTrace + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                    }
                   
                }
                //辅材解析 modify by longb 2023-06-15
                try
                {
                    //SaveMeopAuxMaterial(nod, workflowid, stepid);
                    SaveMeopAuxMaterial2(nod, workflowid, stepid);
                }
                catch (Exception ex)
                {
                    Log.WriteLog("工序：" + specNo + ex.StackTrace, 1, "工序级辅材处理");
                    Log.WriteOrcaleError("PDMTOMES_Workflow" + "@^" + "工序级辅材出错,工序：" + specNo + ex.Message + ex.StackTrace + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   

                }
                //

            }


        }
        #endregion

        #region 附件重新处理 add:Wangjh 20211101

        private void SaveDocumentNew(List<ObjectDocumentEntity> ObjectFileInfo)
        {

            if (ObjectFileInfo.Count == 0)
                return;
            m_DAL = new StandardDAL();
            string strAccessPath = m_AccessoriesPath;
            if (!string.IsNullOrWhiteSpace(m_ProcessNo))
                strAccessPath += @"\" + m_ProcessNo+"$"+m_workflowRev ;
            if (!Directory.Exists(strAccessPath))
            {
                Log.WriteOrcale("PDMTOMES_WorkflowDocument" + "@^" + "未找到附件文件夹" + strAccessPath + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                return;
            }
            foreach (ObjectDocumentEntity obj in ObjectFileInfo) {
                string parentId = "";// m_DAL.GetRDOID("product", "productname", strProductName, "productrevision", strVersion);
                string tableName="";
                switch (obj.type) { 
                    case "spec":
                        tableName = "spec";
                        break;
                    case "workflow":
                        tableName = "workflow";
                        break;
                    default:
                        break;
                }
                if (tableName == "") {
                    return;
                }
                if (string.IsNullOrWhiteSpace(obj.ObjectRev))
                {
                    parentId = m_DAL.GetNDOID(tableName, tableName + "name", obj.ObjectName);
                }
                else {
                    parentId = m_DAL.GetRDOID(tableName, tableName+"name", obj.ObjectName, tableName+"revision", obj.ObjectRev);
                }
                if (string.IsNullOrWhiteSpace(parentId))
                    return;
                if (obj.fileList == null) {
                    return;
                }
                //Debugger.Launch();
                //删除此对象已有的附件信息
                m_DAL.DeleteObjecDocInfo(parentId,m_TempPath );

                var FilesNameList = obj.fileList;
                for (int k = 0; k < FilesNameList.Count; k++)
                {
                    if (!File.Exists(strAccessPath + "\\" + FilesNameList[k]))
                    {
                        Log.WriteLog("未找到文件", 0, FilesNameList[k] + "未找到,跳过处理！");
                        Log.WriteOrcale("PDMTOMES_WorkflowDocument" + "@^" + "未找到文件" + FilesNameList[k] + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                        continue;
                    }
                    string strAA = m_Assistant.uniqName();
                    string strDate = DateTime.Now.ToString("yyyyMMdd");//add by longb 2023-11-01
                    string strTmp1 = m_TempPath + strDate + "\\" + strAA;//modify by longb 2023-11-01  //string strTmp1 = m_TempPath + strAA;
                    if (!Directory.Exists(strTmp1))
                        Directory.CreateDirectory(strTmp1);

                    File.Move(strAccessPath + "\\" + FilesNameList[k], strTmp1 + "\\" + FilesNameList[k]);


                    m_DAL.SaveObjectDocInfo(parentId, "Temp/" + strDate + @"/" + strAA + @"/" + FilesNameList[k], FilesNameList[k]);//modify by longb 2023-11-01

                    Log.WriteOrcale("PDMTOMES_Workflow" + "Document" + "@^" +obj.ObjectName+" 的 "+ FilesNameList[k] + " 附件保存成功" + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                   
                }
            }
            ClearSurplusFile();//最后清理无效附件
        }

        /// <summary>
        /// 清除剩余附件
        /// </summary>
        void ClearSurplusFile(){
            string strAccessPath = m_AccessoriesPath;
            if (!string.IsNullOrWhiteSpace(m_ProcessNo))
                strAccessPath += @"\" + m_ProcessNo;
            if (Directory.Exists(strAccessPath))
            {
                DirectoryInfo di = new DirectoryInfo(strAccessPath);
                  di.Delete(true);
            }
        }
        #endregion

        #region ---特殊过程工序
        /// <summary>
        /// 解析工序节点的特殊过程信息
        /// add:Wangjh 20221129
        /// </summary>
        void SaveMeopSpecialProcess(DataTable SpecialCourseSpecReport, DataTable SpecialCourseSpecParas, XmlNode meopNode, 
            string workflowId, string specId, string stepId)
        {
            //foreach (XmlNode node in meopNode.ChildNodes)
            //{
            XmlNode node = meopNode;
                if (node.Name != "specialProcess")
                    return;
                if (!node.HasChildNodes)
                    return;
                string specialProcessNo = "";
                if (node.SelectSingleNode("specialProcessNo") != null)
                {
                    specialProcessNo = node.SelectSingleNode("specialProcessNo").InnerText;//确认编号
                }
                var equipmentNos = "";//设备编号
                var users = "";//员工号
                string validDate = "";//有效期
                var SpecialCourseSpecReportID = Guid.NewGuid().ToString();
                if (node.SelectSingleNode("datas") != null)
                {
                    foreach (XmlNode data in node.SelectSingleNode("datas").ChildNodes) {

                        if (data.SelectSingleNode("validDate") != null)
                        {
                            validDate = data.SelectSingleNode("validDate").InnerText;//有效期
                        }
                        if (data.SelectSingleNode("equipmentNos") != null && data.SelectSingleNode("equipmentNos").HasChildNodes)
                        {
                            foreach (XmlNode nodec in data.SelectSingleNode("equipmentNos").ChildNodes)
                            {
                                if (nodec.Name == "equipmentNo") { equipmentNos += nodec.InnerText + "、"; }
                            }
                        }
                        if (data.SelectSingleNode("users") != null && data.SelectSingleNode("users").HasChildNodes)
                        {
                            foreach (XmlNode nodec in data.SelectSingleNode("users").ChildNodes)
                            {
                                if (nodec.Name == "user") { users += nodec.InnerText + "、"; }
                            }
                        }
                        if (data.SelectSingleNode("parameters") != null && data.SelectSingleNode("parameters").HasChildNodes)
                        {
                            foreach (XmlNode nodec in data.SelectSingleNode("parameters").ChildNodes)
                            {
                                var name = nodec.SelectSingleNode("name").InnerText;
                                var value = nodec.SelectSingleNode("value").InnerText;
                                DataRow ScSpRow = SpecialCourseSpecParas.NewRow();
                                ScSpRow["SpecialCourseSpecReportID"] = SpecialCourseSpecReportID;
                                ScSpRow["SpecialCourseSpecParasID"] = Guid.NewGuid().ToString(); 
                                ScSpRow["ParaName"] = name;
                                ScSpRow["ParaValue"] = value;
                                SpecialCourseSpecParas.Rows.Add(ScSpRow);
                            }
                        }

                    }
                }
                equipmentNos = equipmentNos.TrimEnd(',');
                users = users.TrimEnd(',');
                DateTime result;
                if (!DateTime.TryParse(validDate, out result)) { validDate = ""; } 
                DataRow ScSrRow = SpecialCourseSpecReport.NewRow();
                ScSrRow["SpecialCourseSpecReportID"] = SpecialCourseSpecReportID;
                ScSrRow["SpecialCourseSpecReportNo"] = specialProcessNo; 
                ScSrRow["EmployeeNames"] = users.TrimEnd('、');
                ScSrRow["ResourceNames"] = equipmentNos.TrimEnd('、');
                ScSrRow["InDate"] = string.IsNullOrWhiteSpace(validDate) ? "" : Convert.ToDateTime(validDate).AddYears(5).ToString("yyyy-MM-dd");//modify by longb 2023-04-17  特殊过程确认报告，默认往后延5年
                SpecialCourseSpecReport.Rows.Add(ScSrRow);

                SpecialCourseSpecReport.AcceptChanges();
                SpecialCourseSpecParas.AcceptChanges();
                //存入数据
                m_DAL.InsertSpecialCourseSpecToMES(SpecialCourseSpecReport, SpecialCourseSpecParas, workflowId, specId, stepId);
                //恢复特殊过程批次暂停为释放 add by zhangrj 2022-12-05
                //m_DAL.UpdateSpecialCourseContainerHold(workflowId);                
            //}
        }

        private DataTable GetDatatableStruct(string type)
        {
            DataTable dt = new DataTable();
            var str = "SpecialCourseSpecReportID,SpecialCourseSpecReportNo,EmployeeNames,ResourceNames,InDate";
            if (type == "1")
            {
                str = "SpecialCourseSpecReportID,SpecialCourseSpecParasID,ParaName,ParaValue";
            }
            foreach (var column in str.Split(','))
            {
                dt.Columns.Add(column, Type.GetType("System.String"));
            }
            return dt;
        }
        #endregion

        #region --yuxj20221101获取工序及工步下的辅材

        /// <summary>
        /// add:Wangjh 20221129 工序辅材处理
        /// </summary>
        /// <param name="meopNode"></param>
        /// <param name="workflowId"></param>
        /// <param name="specId"></param>
        /// <param name="stepId"></param>
        void SaveMeopAuxMaterial(XmlNode meopNode,
            string workflowId,  string stepId)
        {
            if (meopNode.SelectSingleNode("ly2Material") == null)
                return;
            string ly2MaterialAux = meopNode.SelectSingleNode("ly2Material").InnerText.Trim();//辅材
            if (string.IsNullOrEmpty(ly2MaterialAux))
                return ;

            int i = 0;
            foreach (string strSTool in ly2MaterialAux.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                string[] strinfo = strSTool.Split('$');
                string toolID =m_excAPI. CreateAuxMaterial(strinfo);
                if (string.IsNullOrEmpty(toolID))
                    continue;
                i++;
                int qty = 0;
                //yuxj20221121辅材数量取值错误，改为strinfo[4]===》strinfo[5]                
                Int32.TryParse(strinfo[5].Trim(), out qty);
                m_DAL.SaveStepTool(stepId, i, toolID, qty, "0");
            }
        }
        //add by longb 2023-07-13 工序辅材处理
        void SaveMeopAuxMaterial2(XmlNode meopNode, string workflowId, string stepId) 
        {
            if (meopNode.SelectSingleNode("Materials") == null)
                return;
            m_DAL.ClearWorkFlowStepToolAux(stepId);//插入前先清除工序已插入的辅材信息
            int i = 0;
            foreach (XmlNode material in meopNode.SelectSingleNode("Materials").ChildNodes)
            {
                string Material = string.Empty;
                Material += material.SelectSingleNode("code").InnerText + ",";
                Material += material.SelectSingleNode("name").InnerText + ",";
                Material += material.SelectSingleNode("specNo").InnerText + ",";
                Material += material.SelectSingleNode("mark").InnerText + ",";
                Material += material.SelectSingleNode("standard").InnerText + ",";
                Material += material.SelectSingleNode("quallity").InnerText + ",";
                Material += material.SelectSingleNode("remark").InnerText + ",";
                string[] strinfo = Material.Split(',');
                if (strinfo.Length>0) 
                {
                    string toolID = m_excAPI.CreateAuxMaterial(strinfo);
                    if (string.IsNullOrEmpty(toolID))
                        continue;
                    i++;
                    int qty = 0;
                    //yuxj20221121辅材数量取值错误，改为strinfo[4]===》strinfo[5]                
                    Int32.TryParse(strinfo[5].Trim(), out qty);
                    m_DAL.SaveStepTool(stepId, i, toolID, qty, "0");
                }
            }
        }

        #endregion

        #region 工艺更改单--暂停 add by longb 2023-03-13
        public void WorkFlowChangContainerToPause()
        {
            try
            {
                XmlNode meops = m_myXml.SelectSingleNode("/Root/Change");//
                if (!meops.HasChildNodes)
                    return;
                var ly2decisionToProduct = meops.SelectSingleNode("ly2decisionToProduct").InnerText;
                if (!ly2decisionToProduct.Equals("无影响"))
                {
                    var ly2meop_no = meops.SelectSingleNode("ly2meop_no").InnerText;
                    var specNoList=new List<string>();
                    foreach (string specNo in ly2meop_no.Split('、'))
                    {
                        //正则表达式判断是否是数字
                        if (System.Text.RegularExpressions.Regex.IsMatch(specNo, @"^\d+$"))
                        {
                            specNoList.Add(specNo);
                           
                        }
                    }
                    if (specNoList.Count > 0)
                    {
                        m_DAL.suspendContainer("", "", m_workflowName, m_workflowRev, specNoList);//工艺升版 
                    }
                    else {
                        Log.WriteOrcaleError("PDMTOMES_Change" + "@^" + "工艺更改在制批次暂停无处理,工序集：" + ly2meop_no + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
                    }
                }
            }catch(Exception ex){
                Log.WriteLog("工艺更改批次暂停失败："+ex.Message, 1, "工艺更改在制批次暂停处理");
                Log.WriteOrcaleError("PDMTOMES_Change" + "@^" + "工艺更改在制批次暂停处理出错,件号：" + m_workflowName + ":" + m_workflowRev + ex.Message + ex.StackTrace + "@^" + m_FileName + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_strWorkFlowForProduct + ":" + m_strWorkFlowForProductVer);//add:Wangjh 写入数据库   
            }
        }

        #endregion

        #region "会签信息 add by longb 2025-01-08"
        private void SaveWorkflowSignatureInfo() 
        {
            var arrList = new System.Collections.ArrayList();
            var workflowid = m_DAL.GetRDOID("workflow", "workflowname", m_workflowName, "workflow" + "revision", m_workflowRev);
            if (string.IsNullOrWhiteSpace(workflowid))
                return;
            try
            {
                XmlNode reviews = m_myXml.SelectSingleNode("/Root/WorkFlow/REVIEWs");//
                if (reviews==null||!reviews.HasChildNodes)
                    return;
                var ly2design = reviews.SelectSingleNode("ly2design").InnerText;//工艺员
                var ly2designtime = reviews.SelectSingleNode("ly2designtime").InnerText;//编制日期
                var ly2review = reviews.SelectSingleNode("ly2review").InnerText;//审核
                var ly2reviewtime = reviews.SelectSingleNode("ly2reviewtime").InnerText;//审核日期
                var ly2huiqian1 = reviews.SelectSingleNode("ly2huiqian1").InnerText;//会签1
                var ly2huiqian1time = reviews.SelectSingleNode("ly2huiqian1time").InnerText;//会签1日期
                var ly2huiqian1opinion = reviews.SelectSingleNode("ly2huiqian1opinion").InnerText;//会签1意见
                var ly2huiqian2 = reviews.SelectSingleNode("ly2huiqian2").InnerText;//会签2
                var ly2huiqian2time = reviews.SelectSingleNode("ly2huiqian2time").InnerText;//会签2日期
                var ly2huiqian2opinion = reviews.SelectSingleNode("ly2huiqian2opinion").InnerText;//会签2意见
                var ly2huiqian3 = reviews.SelectSingleNode("ly2huiqian3").InnerText;//会签3
                var ly2huiqian3time = reviews.SelectSingleNode("ly2huiqian3time").InnerText;//会签3日期
                var ly2huiqian3opinion = reviews.SelectSingleNode("ly2huiqian3opinion").InnerText;//会签3意见
                var insert = @"insert into WorkflowSignatureInfo(Id,Workflowid,Design,DesignTime,Review,ReviewTime,HuiQian1,HuiQian1Time,HuiQian1Opinion,HuiQian2,HuiQian2Time,HuiQian2Opinion,HuiQian3,HuiQian3Time,HuiQian3Opinion)
                                values(sys_guid(),'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}')";
                var update = @"update WorkflowSignatureInfo set Design='{0}',DesignTime='{1}',Review='{2}',ReviewTime='{3}',
                                HuiQian1='{4}',HuiQian1Time='{5}',HuiQian1Opinion='{6}',HuiQian2='{7}',HuiQian2Time='{8}',
                                HuiQian2Opinion='{9}',HuiQian3='{10}',HuiQian3Time='{11}',HuiQian3Opinion='{12}' where Workflowid='{13}'";
                
                if (m_DAL.Query(string.Format("select * from WorkflowSignatureInfo where Workflowid='{0}'", workflowid)).Rows.Count==0)
                {
                    arrList.Add(string.Format(insert, workflowid, ly2design, ly2designtime, ly2review, ly2reviewtime, ly2huiqian1, ly2huiqian1time, ly2huiqian1opinion, ly2huiqian2, ly2huiqian2time, ly2huiqian2opinion, ly2huiqian3, ly2huiqian3time, ly2huiqian3opinion));
                }
                else {
                    arrList.Add(string.Format(update, ly2design, ly2designtime, ly2review, ly2reviewtime, ly2huiqian1, ly2huiqian1time, ly2huiqian1opinion, ly2huiqian2, ly2huiqian2time, ly2huiqian2opinion, ly2huiqian3, ly2huiqian3time, ly2huiqian3opinion, workflowid));
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("会签信息处理失败：" + ex.Message, 1, "会签信息处理失败");
            }
            m_DAL.ExecuteSqlTran(arrList);
        }
        
        #endregion
    }
}
